Haden Pike
Haden Pike

Reputation: 289

Variables Not Updating From istringstream

So, I've got code like the following:

    #include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cctype>

using namespace std;

int main(int argc, char *argv[])
{
    char c;
    ifstream f("test.txt");
    char n;
    char z;
    char o;
    int output;
    istringstream in;
    string line;
    while (getline(f, line))
    {
        in.str(line);
        do
        {
            c = in.get();
        }
        while (isspace(c));
        in.unget();
        in >> n >> c >> z >> c >> o >> c >> output;
        cout << n << z << o << output << endl;
    in.str(string());
    }
    f.close();
    return 0;
}

and the file test.txt contains:

    A,B,C,1
B,D,F,1
C,F,E,0
D,B,G,1
E,F,C,0
F,E,D,0
G,F,G,0

The format of each line in the text file is "char,char,char,bool" (I'm ignoring the fact that there may be whitespace in the middle of the line, for now).

When I compile and run this code ((using Visual Studio 2010), I get:

ABC1
ABC1
ABC1
ABC1
ABC1
ABC1
ABC1

Obviously, this isn't what I want. Does anyone have an answer as to what's going on here?

Upvotes: 0

Views: 458

Answers (2)

nullptr
nullptr

Reputation: 2284

When you change the content of the stringstream, by default it will set the position pointer to the end of the stream: http://www.cplusplus.com/reference/sstream/stringstream/str/. Add in.seekg(0); after in.str(line); and it should work:

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cctype>

using namespace std;

int main(int argc, char *argv[])
{
    char c;
    ifstream f("test.txt");
    char n;
    char z;
    char o;
    int output;
    istringstream in;
    string line;
    while (getline(f, line))
    {
        in.str(line);
        in.seekg(0);
        do
        {
            c = in.get();
        }
        while (isspace(c));
        in.unget();
        in >> n >> c >> z >> c >> o >> c >> output;
        cout << n << z << o << output << endl;
    in.str(string());
    }
    f.close();
    return 0;
}

Upvotes: 0

masoud
masoud

Reputation: 56479

A quick fix, put istringstream inside the loop to reset the input indicator:

//istringstream in;  ----------+
string line;                   |
while (getline(f, line))       |
{                              |
    istringstream in; <--------+

    in.str(line);
    do
    {
        c = in.get();
    }
    while (isspace(c));
    in.unget();
    in >> n >> c >> z >> c >> o >> c >> output;
    cout << n << z << o << output << endl;
   //in.str(string()); <-------------------- you can remove this line
}
f.close();

If you don't reset the input indicator, the in.get will not work as you expect. or you can simply use seekg(0)

Upvotes: 1

Related Questions