1

What im trying to achieve is to read in data from a .txt file line by line, using getline(), and save it as a string to the variable inVal. I then want to save each individual number that is in the string to an individual element in the objects array by passing it to the member function ArrayBag.add(value). So far I've been able to read in data to inVal fine but nothing I've tried has been able to convert and save the numbers in the string, including the code below after getline(). Please any guidance or tips would be much appreciated.

the .txt file looks like this:

 3  4  5  7  5 16 7 12 11 12  3  9  9  8  1 12
15  4  3  6 1 12  3 12 7  8 19  9 11 12  8  5 -4  -100

My code that ive written so far is like this:

void readInv(ArrayBag &ArrayBag1, ArrayBag &ArrayBag2) {
    //ArrayBag1 and ArrayBag2 are objects of class ArrayBag

    std::string inVal;
    //value to hold each line in file

    std::ifstream readFile;
    readFile.open("setInventory.txt");    //"setInventory.txt" is the txt file being read from.

    if (readFile.is_open()) {
        std::cout << "File is being read." << std::endl;

        while(!readFile.eof()) {
            getline(readFile, inVal);

            for(int i = 0; i < inVal.size(); i++) {
                std::cout << inVal[i] << std::endl;

                ArrayBag1.add(inVal[i] - '0');
                //ArrayBag1.add() is the public member function used to add the
                //passing value to the private member array.
            }
        }
    }
}
Akira
  • 4,100
  • 3
  • 20
  • 39
  • Off topic (but will solve a bug that's coming soon): [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Sep 07 '17 at 05:53
  • 1
    Possible duplicate of [Read file line by line](https://stackoverflow.com/questions/7868936/read-file-line-by-line). Specifically answer 1 option 2. – user4581301 Sep 07 '17 at 05:55
  • Is there a reason you cannot use `std::vector` for this? Vectors are much better than arrays. – Sailanarmo Sep 07 '17 at 06:06
  • Check out top answers here: https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string – K. Kirsz Sep 07 '17 at 06:21
  • @Sailanarmo The assignment prohibits the use of vectors, the class ArrayBag works like a custom vector though so were supposed to use that. – Initium_Novum Sep 07 '17 at 06:52
  • Here you can find very good tips about splitting a string https://stackoverflow.com/questions/236129/most-elegant-way-to-split-a-string – Sinapse Sep 07 '17 at 07:36

1 Answers1

1

i think you can use the stringstream

  stringstream ss{readFile};
  while(ss)
 {
   //doing something
   int a;
   ss>>a;
  ArrayBag1.add(a);
 }
Li Kui
  • 499
  • 4
  • 14