【发布时间】:2021-06-27 23:38:54
【问题描述】:
以下代码假设获取句子的第一个单词(如果有的话)并逐个字母打印(打印部分有效)。我遇到的问题是,每当我在提示中输入一个句子时,它会抓住句子中的每个单词而不是第一个单词(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
【问题讨论】:
-
它一次读取一个单词,但仍会读取您输入的所有单词。下次循环读取第二个单词
-
在
string word[length];中,length不是编译时常量,使word成为可变长度数组,即not standard C++。将length设为const,或改用std::vector。
标签: c++ string while-loop