将输入作为C 中的单词数组

Taking input as array of words in c++

本文关键字:单词 数组 输入      更新时间:2023-10-16
std::vector<std::string> words;
std::string word;
while (std::cin >> word)
words.push_back(word);
cout<<words[1];

我正在使用它进行输入来创建一个用whitespaces创建一系列单词。但是在使用Enter结束句子后,我没有得到任何输出。

我正在使用它进行输入来创建一个用whitespaces创建一系列单词。但是在使用Enter结束句子后,我没有得到任何输出。

那是因为

while (std::cin >> word)
  words.push_back(word);

按下 Enter

时不会停止

std::cin中没有更多数据时,它会停止。您必须输入EOF才能离开while循环。

有用的链接:如何在此程序中输入EOF字符?。

使用

getline(cin,word) 

而不是

cin<<word 

将允许您输入带有空格的单词。

即使,向量开始于索引0,因此输出

words[0]

而不是

words[1]

将输出输入的值。这就是问题。