-1

I have a program which writes data to a file and retrieves it back from the file. When I tried to populate an object using the retrieved values i found out that the values get retrieved as one with out separation. Meaning I have 2 variables named vegetableName and quantity. The data stored is stored in the format of vegetableName quantity.

Eg:- Potato 10

The problem is when am retrieving data from the file, the quantity gets attached to the name, so I cant populate the quantity variable since the quantity is attached to vegetableName.

Here is a screen shot of the program :

enter image description here

As you can in the above screen shot the quantity is attached with the name

But I want it as in the below screen shot

enter image description here

Here is my code for writing data to file:

string fileHandler::writeToFile(Vegetables writeObject)
   {
       ofstream outputFile;
       outputFile.open("my.txt",ios::out|ios::app);

  string dataToWrite=writeObject.toString();
outputFile.write(dataToWrite.c_str(),dataToWrite.size());
    outputFile.close();

return "done";
   }

Here is my file accessing code:

void fileHandler::readFromInventory()
  {
    Vegetables veg; 
    bool stat=true;
    vegetableName;
    int quantity;
          fstream readFile("my.txt",ios::in);
          if(!readFile)
          {
              cerr<<"File Unable to Open"<<endl;
              exit(1);
          }

         while(true)
         {

         if(readFile.eof())
             {
                 break;
             }


             readFile>>vegetableName>>quantity;
              cout<<"Retrieved Vegetable Name:"<<vegetableName<<endl;

             cout<<"Retrieved Quantity       :"<<quantity<<endl;
    ...

What seems to be the problem here ?

tshepang
  • 10,772
  • 21
  • 84
  • 127
Troller
  • 1,004
  • 7
  • 26
  • 42
  • 3
    Your test for `readFile.eof()` is no better than using it as a loop-condtion, [**which is nearly always wrong**](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – WhozCraig Aug 24 '14 at 07:47
  • `if(readFile.eof())` looks wrong for me. You should change this at least to `if(!readFile)` – πάντα ῥεῖ Aug 24 '14 at 07:48
  • 2
    It looks like `Vegetables::toString()` fails to put a space between the name and the quantity. So there is none in the file, and none found when reading it back again. – Ben Voigt Aug 24 '14 at 07:49

1 Answers1

2

Looks like you aren't putting spaces between the vegetable name and quantity.

the filestream variables read values as seperate only if there is white space between them.

(when you output the values to the file, you should put a space between the vegetable names and quantities.)

savageWays
  • 947
  • 6
  • 8