【问题标题】:Using stringstream inside a loop to extract a number from few strings在循环中使用 stringstream 从几个字符串中提取一个数字
【发布时间】:2018-06-10 04:52:30
【问题描述】:

我目前正在练习使用字符串流从字符串中提取值。在这个简单的代码中,用户输入一个名字和一个数字(用空格分隔),这个字符串存储在“input”中。然后,将其传递给“stream”,并将名称和编号分开,分别存储在“name”和“number”中。然后,用 std::cout 输出数字。这个过程用不同的名字和数字完成了几次。

#include <sstream>
#include <iostream>

int main() {
    std::string input;
    std::stringstream stream;
    std::string name;
    double amount;

    for (;;) {
        std::getline(std::cin, input);      // enter a name, a whitespace and a number
        stream.str(input);
        stream >> name >> amount;           // problem here
        std::cout << amount << std::endl;

    }
    return 0;
}

问题:只有第一次输入的输入的数字存储在“金额”中。下一个输入的数字不会存储在“数量”中(数量总是在里面有相同的数字)。也许,关于字符串流,我有些不了解...

【问题讨论】:

  • 如果代码显示两个输入值,即amountname,将更容易看到发生了什么。
  • 我检查了名称,但打印不正确。只打印输入的第一个名字,就像数字一样,只打印第一个输入的数字。不管你循环多少次。
  • @AnselmoGPP 使用一次后需要重置std::stringstream

标签: c++ for-loop stringstream


【解决方案1】:

问题:只有第一个输入的数字被存储在 “数量”。下一个输入的数字将不会存储在 “金额”(金额中的数字始终相同)。也许,有 关于字符串流我不知道的事情......

是的。 std::stringstream 使用一次后忘记重置

为此,您需要使用std::stringstream::str基础序列(字符串流的内容)设置为空字符串,同时失败(如果有)和 eof 标志clear

这意味着,在您的 for 循环结束时,您需要这个:SEE LIVE

int main()
{
   ....
   ....
   for (;;)
   {
      ...
      ...
      stream.str( std::string() );   // or stream.str(""); 
      stream.clear();
   }
   return 0;
}

【讨论】:

  • 我检查了一下,stream.clear() 解决了这个问题(谢谢!)。但是,stream.str(std::string())stream.str("") 并不是程序正常工作所必需的。
  • 好的。因此,要真正重置字符串流,您必须 stream.str(std::string())stream.clear()。我会记住的。在这个小程序中,不一定要擦除 stringstream 的内容,因为它们稍后会被覆盖,但很高兴知道。谢谢。
【解决方案2】:

尝试使用 Input StringStream std::istringstream 代替,它专门用作输入流(如 std::cin),不像 std::stringstream

#include <sstream>
#include <iostream>

int main() {
    std::string input;
    std::istringstream stream; // Note the extra i
    std::string name;
    double amount;

    for (;;) {
        std::getline(std::cin, input);
        stream.str(input);
        stream >> name >> amount;
        std::cout << amount << std::endl;

    }
    return 0;
}

输入:你好 3.14

输出:3.14

输入:世界 2.71

输出:2.71

【讨论】:

  • @HansGP 你确定你在istringstream 中添加了额外的i 吗?
  • 是的,Gill Bates,我已经尝试过多次了。我什至复制了你的代码并编译了它。它仍然无法按预期工作。这很奇怪......也许是编译器问题?我正在使用 Visual Studio Community 2017
【解决方案3】:

问题是调用str(string)时读取位置未定义。 结果stream 进入错误状态here is a proof

修复它的最佳方法是在循环内移动stream 的范围:

#include <sstream>
#include <iostream>

int main() {
    std::string input;
    std::string name;
    double amount;

    while (std::getline(std::cin, input)) {
        std::stringstream stream(input);
        stream >> name >> amount;
        std::cout << amount << " " << name << std::endl;

    }
    return 0;
}

这里是proof that it works。其实最好转more variables inside a loop

【讨论】:

  • 是的,在循环内移动字符串流变量声明可以解决问题。谢谢你。 @JeJo 还提供了一个我认为更有效的解决方案(使用 stream.clear())。
猜你喜欢
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多