【发布时间】:2018-09-19 11:59:09
【问题描述】:
无论我输入什么(按回车键时),我的程序一旦到达 getline() 函数就会冻结。
有什么方法可以解决 getline 的这种用法,或者我可以在 C/C++ 中实现任何替代输入流吗?
示例输入:查询 20130105 string1 string2
puts("a");
string line;
getline(cin, line);
puts("b");
string words[4] = {"", "", "", ""};
int wordCount = 0;
for(int i = 1; i < line.length(); i++) {
puts("c");
string currentsub = line.substr(i-1, i);
if(currentsub != "\t")
words[wordCount] += currentsub;
else
wordCount++;
}
【问题讨论】:
-
您的意思是对
getline()的调用本身没有返回,或者您用来解析该行的代码被挂断了? -
@TrippKinetics 本质上 getline() 正在接受无限输入
-
你是说像
int main() { string line; getline(cin, line); cout << line; }这样的东西在你运行时挂起并且不打印任何东西? -
while(line.substr(i-1, i) != "\t") { words[wordCount] += line.substr(i-1, i);}这个循环将一直运行,直到字符串耗尽所有可用内存(此时程序将崩溃,但您必须等待一段时间)。你一遍又一遍地检查和附加line[0]。 -
在这种情况下,
getline调用可能会等待输入。您认为您提供给它的输入可能以前在其他地方使用过,在您未显示的代码中。一方面,我发现很难推理我看不到的代码;如果您有兴趣进一步讨论,请准备并显示minimal reproducible example。
标签: c++ input inputstream