首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >串流清除故障

串流清除故障
EN

Stack Overflow用户
提问于 2015-02-09 21:59:44
回答 3查看 642关注 0票数 0

我使用stringstream将数字字符串转换为整数。我不知道为什么遵循的代码不起作用。有人能解释一下为什么我总是得到tmp变量的相等值吗?

代码语言:javascript
复制
#include <fstream>
#include <string>
#include <sstream>
#include <cctype>

int main() {
    std::ifstream input("input.txt");
    std::ofstream output("output.txt");
    std::string str = "", line;
    std::stringstream ss;
    int tmp;
    while (std::getline(input, line)) {
        for (int i = 0, l = line.size(); i < l; i++) {
            if (isdigit(line[i]))
                str += line[i];
        }
        ss << str;
        // gets int from stringstream
        ss >> tmp;
        output << str << ' ' << tmp << std::endl;
        str = "";
        // stringstream clearing
        ss.str("");

    }

    return 0;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-02-09 22:23:29

之后

代码语言:javascript
复制
ss >> tmp;

ss在EOF。那工作结束后,所有的阅读都没有。您可以添加一行

代码语言:javascript
复制
ss.clear();

之后

代码语言:javascript
复制
ss.str("");

来清理其内部状态。它会开始运作的。我用一个if语句来检验这个假设。

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cctype>

int main() {
    std::ifstream input("input.txt");
    std::string str = "", line;
    std::stringstream ss;
    int tmp;
    while (std::getline(input, line)) {
        for (int i = 0, l = line.size(); i < l; i++) {
            if (isdigit(line[i]))
                str += line[i];
        }
        ss << str;
        // gets int from stringstream
        ss >> tmp;
        std::cout << str << ' ' << tmp << std::endl;
        str = "";
        // stringstream clearing

        if (ss.eof())
        {
           std::cout << "ss is at eof\n";
        }

        ss.str("");
        ss.clear();

    }

    return 0;
}
票数 2
EN

Stack Overflow用户

发布于 2015-02-09 22:24:05

要重置std::stringstream,首先必须使用std::basic_stringstream::str设置缓冲区的内容,然后用std::basic_istream::seekg重新设置输入位置,

代码语言:javascript
复制
ss.str(str);
ss.seekg(0);
ss >> tmp;
票数 1
EN

Stack Overflow用户

发布于 2015-02-09 22:39:27

作为您必须在每次迭代时清除stringstream的替代方法,正如@ Sahu所提到的那样,您可以在while循环中声明std::stringstream ss。这样,您可以在每次迭代结束时销毁变量,并在每次执行while循环时创建一个新变量。

代码语言:javascript
复制
#include <fstream>
#include <string>
#include <sstream>
#include <cctype>

int main()
{
    std::ifstream input("input.txt");
    std::ofstream output("output.txt");
    std::string line;

    while (std::getline(input, line))
    {
        std::string str;
        std::stringstream ss;
        int tmp;

        for (int i = 0; i < line.size(); i++)
        {
            if (isdigit(line[i]))
                str += line[i];
        }
        ss << str;
        // gets int from stringstream
        ss >> tmp;
        output << str << " " << tmp << std::endl;
    }

    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28420228

复制
相关文章

相似问题

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