在C++中的while循环条件中的Cin
Cin in a while loop condition in C++
下面的代码假设获取一个句子的第一个单词(如果有(,并逐字母打印(打印部分可以工作(。我遇到的问题是,每当我在提示中输入一个句子时,它会抓住句子中的每个单词,而不是第一个单词(假设cin停在第一个空格,输入等等……所以我认为这里错误的部分是while循环(。如何解决此问题?我想有些事情我不理解。
#include <iostream>
using namespace std;
int main(void){
int i = 0;
int length= 25;
string word[length];
cout << "Type another word: (Press Ctrl + D to quit):";
while( i < length && cin >> word[i]){
i++;
cout << "Type another word: (Press Ctrl + D to quit):";
}
for(int j = 0; j < i; j++){
cout<< endl << word[j]<< endl;
for(int k = 0; k < word[j].length(); k++)
cout << word[j].at(k) << endl;
}
}
正如我们所看到的,这抓住了整个句子,因此它打印了另一个不需要的提示。
输出示例:
Type another word: (Press Ctrl + D to quit):testing this
Type another word: (Press Ctrl + D to quit):Type another word: (Press Ctrl + D to quit):december
Type another word: (Press Ctrl + D to quit):
testing
t
e
s
t
i
n
g
this
t
h
i
s
december
d
e
c
e
m
b
e
r
我将附上一个"理想"输出:
Type another word: (Press Ctrl + D to quit):testing this
Type another word: (Press Ctrl + D to quit):december
Type another word: (Press Ctrl + D to quit):
testing
t
e
s
t
i
n
g
december
d
e
c
e
m
b
e
r
当你写时,假设cin停在第一个空格,输入等等……所以我认为这里错误的部分是while循环,你几乎把它搞定了。cin >> words[i]
在数组中读取一个单词。循环体递增i
,然后再次进行读取。逐字逐句。不是下一句。下一个单词。操作员>>
不懂句子。只是说说而已。
相反,使用std::getline
读取整行,然后从该行中获取第一个单词。最简单的方法可能是将行转换为std::istringstream
,并使用运算符>>
提取单个单词。
例如:
#include <iostream>
#include <string> // was missing.
#include <sstream> // defines std::istringstream
using namespace std;
int main(){ // no need for void. Compiler's smart enough to figure
// that out from empty braces.
int i = 0;
const int length= 25; // needs to be constant to be used to size
// an array
string word[length];
cout << "Type another word: (Press Ctrl + D to quit):";
std::string line; // storage for the line
while( i < length && std::getline(cin, line)){ //read whole line
std::istringstream strm(line); // make a stream out of the line
if (strm >> word[i]) // read first word from line
{
i++;
}
else // tell user they made a mistake or do something fancy.
{
std::cout << "No word on that line.n";
}
cout << "Type another word: (Press Ctrl + D to quit):";
}
for(int j = 0; j < i; j++){
cout<< endl << word[j]<< endl;
for(int k = 0; k < word[j].length(); k++)
cout << word[j].at(k) << endl;
}
}
std::getline
文档
std::istringstream
文档
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- C++中的cin.ignore()函数不适用于整个流
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 似乎多余的使用 cin 作为条件与 if,而
- 为什么"cin >>"可以作为条件
- 在接收带有 CIN 条件的输入时按回车键时出现奇怪的行为
- 如何在条件表达式中使用 'cin' 正确退出 while 循环?(C++,CLion)
- if(!getline(std::cin,str1))break;这个条件检查什么
- 为什么使用 cin 作为循环条件
- c++中while循环条件中使用std::cin的行为
- (cin >> buf && !buf.empty()) 中的第二个条件是多余的吗?
- if (cin >> x) - 为什么你可以使用该条件?