-1

So i am working on my project and i am facing a problem. Every time i try to input data from file in c++ i got blank screen

The code :

int main() {

string make[1000],model[1000],partName[1000];
int partNo[1000],quantity[1000];
double price[1000];
int i = 0;

ifstream myFile("file.txt");
while (!myFile.eof())
{
    myFile >> make[i] >>model[i]>> partNo[i] >>quantity[i]>> price[i]>>partName[i];
    i++;
}
for (int j = 0;j < i;j++)
    cout << make[j] <<"\t"<<model[j]<<"\t"<< partNo[j] <<"\t"<<quantity[j]<<"\t"<< price[j]<<"\t"<<partName[j]<<endl;
    return 0;

}

a sample from data file :

Pajero  NA1H25    1     26      3.65     BLADE W/S WIPER
Pajero  NA1S25    2     12      65.7     OIL SEAL-T/M CASE
Pajero  NA3H25    3     20      14.6     OIL SEAL-DIST
Pajero  NA3H25    4     26     10.95     DISC-CLUTCH
Pajero  NC3V25    5     13      14.6     FUSIBLE LINK
Pajero  ND0000    6     12      3.65     WEATHERSHIELD PKGE-L
Pajero  ND1V45    7     10     32.85     SEAL & BOOT KIT
Pajero  ND1Z45    8     24     62.05     FUSIBLE LINK
Pajero  ND1Z45    9      9     18.25     COVER-HANDLE LH
Pajero  ND1Z45   10      6      3.65     PIPE ASSY-OIL

anyone can help ??

N9ne
  • 1
  • 1

1 Answers1

1

Input with operator >> to a std::string will only read a single word.

This means that the first input will read "BLADE" and leave "W/S WIPER" in the input buffer, and the next read will start from there. Eventually, an input operation for a numeric field will try to read letters, and fail to read.

After that the stream is in a bad condition and nothing else is read, even though myfile.eof() is not true (but myfile.fail() is). There you have an infinite loop. See Why is iostream::eof inside a loop condition considered wrong?

Community
  • 1
  • 1
Bo Persson
  • 86,087
  • 31
  • 138
  • 198
  • ok is there any way i can make it read the whole word or i must delete the spaces ? – N9ne Dec 24 '15 at 23:50
  • You can possibly read the whole line into a single string with `std::getline` and then parse that string into the variables. Or read the first 5 fields the way you do now, and then use a `getline` for the last part. – Bo Persson Dec 24 '15 at 23:51