【问题标题】:C++ getline() doesn't end inputC++ getline() 不结束输入
【发布时间】:2013-03-03 10:46:23
【问题描述】:
string str, temp;

string c;

cout << "Insert the character that ends the input:" << endl;

getline(cin, c);

cout << "Insert the string:" << endl;

getline(cin, str, c.c_str()[0]);

我应该能够在字符串“test”中放入一个字符串,直到我输入结束字符,但是如果我输入一个双新行,它就无法识别结束字符并且它不会结束输入。

这是输出:

Insert the character that ends the input:
}
Insert the string:
asdf

}
do it}
damn}

【问题讨论】:

  • 您的代码和示例输出不同。你能发布正确的吗
  • 您的代码对我有用。但我会直接使用char 来代替c
  • c[0] 而不是 c.c_str()[0] 也可以,但我无法重现这种行为(g++-4.7,Ubuntu 12.10)。
  • 我有 LLVM 并且使用 c[0] 不起作用
  • @fpiro 我假设您的意思是 clang 或 llvm-gcc(llvm 本身不是编译器)。在任何一种情况下,这都应该可以正常工作。

标签: c++ string input getline


【解决方案1】:

您可能想要稍微重新设计您的代码,例如如果分隔符是一个字符,那么为什么要读取string(并使用一种像“c.c_str()[0]”这样的晦涩语法——至少只使用c[0]从字符串中提取第一个字符)?只需阅读单个分隔符即可。

此外,我没有看到来自getline() 的意外结果。

如果你试试这个代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Insert the character that ends the input: " << endl;  
    char delim;
    cin >> delim;

    string str;   
    cout << "Insert the string: " << endl;   
    getline(cin, str, delim);

    cout << "String: " << str << endl;
}

输出符合预期,例如输入字符串“hello!world”在分隔符“!”处被截断,结果为“hello”:

C:\TEMP\CppTests>cl /EHsc /W4 /nologo /MTd test.cpp
test.cpp

C:\TEMP\CppTests>test.exe
Insert the character that ends the input:
!
Insert the string:
hello!world
String:
hello

【讨论】:

  • 谢谢大家,我发现这个错误在这个输入之后的算法中。
【解决方案2】:

把代码改成

getline(cin, str, c[0]);

【讨论】:

  • @Predheep - c 是一个字符,不允许下标一个单纯的字符类型。
猜你喜欢
  • 2012-11-12
  • 2013-11-09
  • 2011-12-15
  • 2019-06-16
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
相关资源
最近更新 更多