【问题标题】:how to get my string commands by getline() and stringstream如何通过 getline() 和 stringstream 获取我的字符串命令
【发布时间】:2015-08-16 04:58:16
【问题描述】:

我想知道我是否使用正确的形式将我的命令放在一行中,然后通过ifs 获取每个命令所需的信息。这是我的代码的一部分;实际上,我的main 函数的第一部分:

string line;
stringstream ss;

while (!cin.eof())
{
    getline(cin, line);
    //i dont know if next line should be used   
    ss << line;
    if (line.size() == 0)
        continue;

    ss >> command;

    if (command == "put")
    {
         string your_file_ad, destin_ad;
         ss >> your_file_ad >> destin_ad;
         //baraye history ezafe shod
         give_file(your_file_ad, p_online)->index_plus(command);

【问题讨论】:

  • 我想你想根据命令的值做一些处理,并将每个命令的详细信息写在字符串流上,对吗?
  • 是的,基于什么命令我会从用户那里得到不同的信息...
  • 谁教你写while (!cin.eof())?那是不正确

标签: c++ getline stringstream


【解决方案1】:

我尝试在您的 if 中添加两个 couts 来运行您的代码,以查看例如当用户输入 put a b 时会发生什么。

所以,这是我的代码:

string line;
stringstream ss;
while (true)
{
    getline(cin, line);
    //i dont know if next line should be used   

    ss << line;
    if (line.size() == 0)
        continue;

    string command;
    ss >> command;

    if (command == "put")
    {
        string your_file_ad, destin_ad;
        ss >> your_file_ad >> destin_ad;
        cout << "input #1 is " << your_file_ad << endl;
        cout << "input #2 is " << destin_ad << endl;
    }
}

当我运行这段代码时,如果我在控制台中写put a b,我会看到这个结果,这是正确的:

input #1 is a
input #2 is b

但似乎这个 only 适用于第一个命令。之后命令无法正确处理。

所以,我又读了一遍代码,发现问题是,你在 while 之外初始化你的 stringstream

我不确定它到底为什么不起作用(可能已经达到 EOF 并且无法继续阅读?),但如果你在 while 内移动 stringstream ss;,它会正常工作:

string line;
while (true)
{
    stringstream ss;

    getline(cin, line);
    //i dont know if next line should be used   

    ss << line;
    if (line.size() == 0)
        continue;

    string command;
    ss >> command;

    if (command == "put")
    {
        string your_file_ad, destin_ad;
        ss >> your_file_ad >> destin_ad;
        cout << "input #1 is " << your_file_ad << endl;
        cout << "input #2 is " << destin_ad << endl;
    }
}

更新:阅读下面关于第一个代码问题的@LightnessRacesinOrbit 评论。

【讨论】:

  • 不,您也在使用while (!cin.eof())。立即停止这样做!当你修复了这个错误时让我知道,这样我就可以删除我的反对票。
  • 而且,是的,问题是在字符串流上设置了 EOF 位。如果您重置它的内容和标志,您可以重新使用它,但也可以使其受范围约束。
  • @LightnessRacesinOrbit 这与问题想要什么无关,但无论如何我都会用一个简单的while (true) 替换它:) 提问者可以根据他的需要将其更改为任何必要的内容。另外,感谢您对 EOF 的评论。我会用更多细节更新答案。
  • OP 想要有效的代码和正确的建议。只要您传播这种误解while (!cin.eof()) 废话,您的答案就不能满足这些标准。将其更改为while (true) 不能解决问题。它实际上在您的屏幕截图中显示了这一点:您不想要的一个额外的循环迭代。仔细阅读this。然后再读一遍。然后打电话给教你写字的人while (!cin.eof()),并告诉他们阅读。
猜你喜欢
  • 2017-09-28
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-06-03
  • 2021-04-07
  • 2012-05-21
  • 1970-01-01
  • 2011-03-08
相关资源
最近更新 更多