gpt4 book ai didi

c++ - 读取一系列单词以将它们添加到 vector 中

转载 作者:搜寻专家 更新时间:2023-10-31 01:51:01 25 4
gpt4 key购买 nike

我最近买了一个C++ Primer并陷入了一个问题。我必须使用 cin 读取一系列单词并将值存储在 vector 中。在遇到异常问题后,我发现如果您期望输入无效,while(cin >> words) 会引发问题(如无限循环):Using cin to get user input

int main()
{
string words;
vector<string> v;
cout << "Enter words" << endl;
while (cin >> words)
{
v.push_back(words);
}
for(auto b : v)
cout << b << " ";
cout << endl;
return 0;
}

因此,我正在尝试寻找解决此问题的方法。帮助?

最佳答案

您提供的关于输入问题的链接有点不同。它谈论的是您何时希望用户输入特定值,但您可能无法读取该值(假设它是一个整数),因为输入了其他内容。在这种情况下,最好使用 getline 检索整行输入,然后解析出值。

在你的情况下,你只是在追求文字。当您从流中读取一个字符串时,它将为您提供所有连续的非空白字符。而且,暂时忽略标点符号,你可以称其为“词”。因此,当您谈论“无效输入”时,我不明白您的意思。循环会继续给你“单词”,直到流中没有剩余,此时它会出错:

vector<string> words;
string word;
while( cin >> word ) words.push_back(word);

但是,如果您希望用户在一行中输入所有单词并按回车键完成,则需要使用 getline:

// Get all words on one line
cout << "Enter words: " << flush;
string allwords;
getline( cin, allwords );

// Parse words into a vector
vector<string> words;
string word;
istringstream iss(allwords);
while( iss >> word ) words.push_back(word);

或者你可以这样做:

cout << "Enter words, one per line (leave an empty line when done)\n";

vector<string> words;
string line;
while( getline(cin, line) )
{
// Because of the word check that follows, you don't really need this...
if( line.size() == 0 ) break;

// Make sure it's actually a word.
istringstream iss(line);
string word;
if( !(iss >> word) ) break;

// If you want, you can check the characters and complain about non-alphabet
// characters here... But that's up to you.

// Add word to vector
words.push_back(word);
}

关于c++ - 读取一系列单词以将它们添加到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14347033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com