0

所以,我有如下代码:

    #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;
}

并且文件 test.txt 包含:

    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

文本文件中每一行的格式是“char,char,char,bool”(我暂时忽略了行中间可能有空格的事实)。

当我编译并运行此代码((使用 Visual Studio 2010)时,我得到:

ABC1
ABC1
ABC1
ABC1
ABC1
ABC1
ABC1

显然,这不是我想要的。有人对这里发生的事情有答案吗?

4

2 回答 2

1

快速修复,放入istringstream循环中以重置输入指示器:

//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();

如果您不重置输入指示器,in.get则将无法按预期工作。或者你可以简单地使用seekg(0)

于 2013-05-02T19:14:51.760 回答
0

当您更改字符串流的内容时,默认情况下它将位置指针设置为流的末尾:http ://www.cplusplus.com/reference/sstream/stringstream/str/ 。添加in.seekg(0);之后in.str(line);,它应该可以工作:

#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;
}
于 2013-05-02T19:15:16.033 回答