下面的代码假设抓取一个句子的第一个单词(如果有),并逐个字母地打印它(打印部分可以工作)。我遇到的问题是,每当我在提示符中输入一个句子时,它会抓住句子中的每个单词,而不是第一个单词(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
发布于 2021-03-31 23:54:33
当你写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;
}
}
https://stackoverflow.com/questions/66896613
复制相似问题