samedi 20 octobre 2018

Loop not handling '\n' comparison properly

I am trying to read from an input file with this general format:

1 2 3
2 1
3 1

To construct an adjacency list for a graph. I made a function to get the next number in the sequence, which is written to stop when either a space or '\n' is being detected. However, the comparison of my nextChar to '\n' is not causing it to exit the loop, and the stoi() is throwing an std::invalid_argument, which I thought I had accounted for in my while loop. I am not sure what I am doing wrong here, and I don't know how to fix my code to work the way I want it to.

int getNumber(ifstream &input, string &inputStr, char &nextChar) {

inputStr.clear();

// Append digits to the string until either a space or newline is encountered.
while(nextChar != ' ' && nextChar != '\n')
{
    inputStr.append(1, nextChar);

    input.get(nextChar);
}

int number = stoi(inputStr);

return number;

Aucun commentaire:

Enregistrer un commentaire