C++中如何终止cin输入循环?新手代码运行疑问
如何终止cin>>temp的输入循环?附循环工作原理解析
一、终止输入的方法
cin>>temp会自动跳过所有空白字符(包括回车、空格、制表符),所以单纯按回车无法终止输入。要结束输入,需要触发EOF(文件结束符):
- Windows系统:输入完所有单词后,按下
Ctrl+Z再按回车 - Linux/macOS系统:输入完所有单词后,按下
Ctrl+D
二、for循环的工作原理
你代码中的循环写法是C++读取输入的常用范式:
for(string temp; cin>>temp; )
逻辑拆解如下:
- 初始化:循环启动前创建临时字符串变量
temp - 条件判断:执行
cin>>temp尝试从输入流读取一个以空白符分隔的单词。这个操作返回cin对象本身——当读取成功时,cin会被隐式转换为bool值true,循环继续;当遇到EOF或输入无法解析为字符串时,cin进入失败状态,转换为bool值false,循环终止。 - 循环体:每次成功读取单词后,将
temp存入vector容器中
三、代码错误修正
你的示例代码存在两处运行报错的问题:
sort(words);调用错误:标准库sort函数需要传入容器的起始和结束迭代器,正确写法为:
同时需在代码开头包含sort(words.begin(), words.end());<algorithm>头文件words[i–1]中的减号是中文全角符号,需改为英文半角减号words[i-1]
修正后的完整代码:
#include <iostream> #include <vector> #include <string> #include <algorithm> // simple dictionary: list of sorted words int main() { std::vector<std::string> words; for(std::string temp; std::cin>>temp; ) // read whitespace-separated words words.push_back(temp); // put into vector std::cout << "Number of words: " << words.size() << '\n'; std::sort(words.begin(), words.end()); // sort the words for (int i = 0; i<words.size(); ++i) if (i==0 || words[i-1]!=words[i]) // is this a new word? std::cout << words[i] << "\n"; }
内容的提问来源于stack exchange,提问作者user10217630
相关产品推荐
相关产品推荐

