【问题标题】:istringsteam with line breaksistringsteam 带换行符
【发布时间】:2015-01-31 18:48:58
【问题描述】:

好的,我读到了,如果我们有一个字符串 s =" 1 2 3"

我们可以做到:

istringstream iss(s);  
int a;
int b;
int c;

iss >> a >> b >> c;

假设我们有一个包含以下内容的文本文件:

测试1
100 毫秒

测试2
200 毫秒

测试3
300 毫秒

ifstream in ("test.txt")
string s;
while (getline(in, s))
{
       // I want to store the integers only to a b and c, How ?
}

【问题讨论】:

    标签: c++ istringstream


    【解决方案1】:

    1) 您可以依赖成功的 int 转换:

    int value;
    std::string buffer;
    while(std::getline(iss, buffer,' ')) 
    {
        if(std::istringstream(buffer) >> value)
        {
            std::cout << value << std::endl;
        }
    }
    

    2) 或跳过不必要的数据:

    int value;
    std::string buffer;
    while(iss >> buffer) 
    {
        iss >> value >> buffer;
        std::cout << value << std::endl;
    }
    

    【讨论】:

    • 第一种方法成功打印整数值,但是如何将它们解析为 int a , int b 和 int c 因为它们仅根据代码存储在“int value”中!
    • @TharwatHarakeh,您可以将它们存储在动态数组std::vector v; 中,而不是std::cout &lt;&lt; value &lt;&lt; std::endl; 写入v.push_back(value)。之后,如果您愿意:int a = v[0], b = v[1], c = v[2];
    • 你能提供一个完整的工作代码吗?我试过你说的,但我不能让它工作
    • 代码:pastebin.com/53LuYVGN 这里是错误prntscr.com/5zo41l
    • 看起来你的输入文件的整数少于3个,例如当你尝试调用v[2]时,没有这样的元素
    【解决方案2】:

    如果您知道文本文件中详细信息的模式,则可以解析所有详细信息,但只存储 int 值。例如:

    ifstream in ("test.txt")
    string s;
    while (getline(in, s))
    {
         getline(in,s); //read the line after 'test'.
         string temp;
         istringstream strm(s);
         s >> temp;
         int a = stoi(temp) // assuming you are using C++11. Else, atoi(temp.c_str())
         s >> temp;
         getline(in,s); // for the line with blank space
    }
    

    上面的代码仍然有点不雅。除此之外,您可以做的是在 C++ 中使用随机文件操作。它们允许您移动指针以从文件中读取数据。更多信息请参考此链接:http://www.learncpp.com/cpp-tutorial/137-random-file-io/

    PS:我没有在我的系统上运行此代码,但我想它应该可以工作。第二种方法确实有效,因为我以前使用过它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2017-01-23
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多