gpt4 book ai didi

c++ - while循环后的语句不执行

转载 作者:太空狗 更新时间:2023-10-29 20:59:57 26 4
gpt4 key购买 nike

我在使用 while 循环时遇到问题。 while 循环后的语句没有执行,我不知道为什么。我是 C++ 的新手,无法弄清楚这一点。我试图将一些单词作为用户的输入并将它们存储在字符串 vector 中,只是为了练习。这是我的代码:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

int _tmain(int argc, _TCHAR* argv[])
{
vector<string> list;
string word;

while( cin >> word )
{
list.push_back(word);
cout << "Added " << word << endl;
}

cout << endl;
cout << "Done" << endl;

system( "PAUSE" );
return EXIT_SUCCESS;
}

当我运行这个控制台应用程序时,我可以看到 while 循环中的语句已执行,并且消息“已添加”但未显示消息“完成”。我已经通过在 while 循环之后指定其他语句(例如 for 循环从同一字符串 vector 中获取和显示值)来尝试此操作,但是在执行此 while 循环之后没有语句。只执行 while 循环之前和之内的语句,我不知道为什么。

最佳答案

只要您输入有效的字符串,循环就会继续。并且只输入一个空行是行不通的,因为输入运算符将一直阻塞,直到它读取到一个非空白字符。您实际上需要通过按 CTRL-Z(文件结束键盘快捷键)来“终止”字符串。


如果你想检测空行并将其用于终止条件,你需要使用 std::getline :

std::string line;
while (std::getline(std::cin, line) && !line.empty())
{
...
}

关于c++ - while循环后的语句不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23363327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com