在C++中的while循环条件中的Cin

Cin in a while loop condition in C++

本文关键字:Cin 条件 循环 C++ 中的 while      更新时间:2024-05-10

下面的代码假设获取一个句子的第一个单词(如果有(,并逐字母打印(打印部分可以工作(。我遇到的问题是,每当我在提示中输入一个句子时,它会抓住句子中的每个单词,而不是第一个单词(假设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文档