Captain n00b
Captain n00b

Reputation: 63

How to move through each line in getline()

Whenever I run my code, I get the first line pulled out of the file, but only the first. Is there something I am missing? I ran into the issue when I implemented stringstream to try and more easily read in the lines of hex from the file and more quickly convert between a string to a hex value. It read in each line accordingly before, but now it is not. Am I missing something in the understanding of how getline() works?

ss is stringstream, fileIn is the file, hexInput is a string, memory[] is an array of short int, instruction is a short int, opCounter is an int...

string hexInput;
stringstream ss;
short int instruction;
ifstream fileIn ("proj1.txt");

if (fileIn.is_open())
{
    while ( getline(fileIn, hexInput) ) 
    {
        ss << hex << hexInput;
        ss >> instruction;

        memory[opCounter] = instruction;

        cout << hex << memory[opCounter] << '\t';
        cout << opCounter << '\n';

        ss.str("");
        opCounter++;
    }
    fileIn.close();
}
else cout << "Unable to open file";

Above is the entire function (which was working before using stringstream) and below are the contents of the file.

4000
0033
0132
2033
4321
2137
D036
A00F
B003
C00C
3217
6217
E044
FFFF
6016
1013
FFFF
0
0
0
0
1
2
3
4
5

There are 26 lines and the last opCounter output says "19" in hex which makes me assume the file is being read line-by-line, but the stringstream never updated. This is my first C++ program and am new to a few of these features I am trying to implement. Thanks for any help...

Upvotes: 1

Views: 1165

Answers (1)

example
example

Reputation: 3419

Your stringstream is created correctly from the first line. After outputting the number into instruction it will be eof though (you can check this with ss.eof()) because there is no data after the first number inside the stringstream.

replace ss.str(""); (which you don't need) by ss.clear(); which will reset the eof flag. Inputting the new line and reading from the stream will then work as expected.

Of course there is absolutely no need for a stringstream in the first place.

while ( fileIn.good() ) {
    fileIn >> hex >> instruction;
    [...]
}

works fine. It will read short ints in hexadecimal representation until one line cannot be interpreted as such. (Which incidentally is line 7 because D036 is too large to fit inside a short int - admittedly that is different from your current behaviour, but did you really want a silent failure? very useful at this point are again fileIn.eof() to check whether the read failed due to the stream being at the end of the file and fileIn.clear() to reset other fail-bits)

As requested: The loop is commonly abbreviated as

while ( fileIn >> hex >> instruction ) {
    [...]
}

but note, that if you want to check why the read failed, and continue if it was not an eof, the aforementioned loop is more suited to the task.

Upvotes: 2

Related Questions