首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >变量不从istringstream更新

变量不从istringstream更新
EN

Stack Overflow用户
提问于 2013-05-03 03:09:06
回答 2查看 336关注 0票数 0

所以,我得到了如下代码:

代码语言:javascript
复制
    #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包含:

代码语言:javascript
复制
    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,bool“(我暂时忽略了行中间可能有空格的事实)。

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

代码语言:javascript
复制
ABC1
ABC1
ABC1
ABC1
ABC1
ABC1
ABC1

显然,这不是我想要的。有没有人知道这是怎么回事?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-03 03:14:52

一个快速的解决方法是,将istringstream放入循环中以重置输入指示器:

代码语言:javascript
复制
//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)

票数 1
EN

Stack Overflow用户

发布于 2013-05-03 03:15:16

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

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16345887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档