Question

I'm really frustrated. I'm trying to read a txt file which has the following content:

Arenas
Edward
239924731
2525976612

Autry
Richard
527646269
6028236739

Using this code :

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main(int argc, const char * argv[])
{
     string line;
     string last, first;
     int uin, number;
     ifstream phoneBook;
     phoneBook.open("PhoneBook.txt");

    while (!phoneBook.eof()) {
        phoneBook >> last >> first >> uin >> number;
        cout << last << ", " << first << ", " << uin << ", " << number <<endl;
    }




    return 0;
}

The output would be the same contact endlessly

Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647
Arenas, Edward, 239924731, 2147483647

I also tried this version of while loop:

while (phoneBook >> last >> first >> uin >> number) {

    cout << last << ", " << first << ", " << uin << ", " << number <<endl;
}

For some reasons, the compiler doesn't even step into the loop. It would just jump to return 0;

Was it helpful?

Solution

Your number values are too big to fit into a four-byte signed integer. Maximum value for that is 2147483647 (2^31 - 1), which is why you get that printing out at the end. (You weren't asking about that issue; I don't know how I noticed it myself!)

But what I'm also wondering about is that extra line that you have in between each record. I found this question that discusses fstreams and delimiters. I wonder if it's getting stuck at the blank line, reading nothing, and then just outputting the same values of last, first, uin, and number.

OTHER TIPS

There may be a different type of error. The best method to use is ios::good:

while (!phoneBook.good()) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top