我最近选择了编码C ++,我正在学习使用Bjarne Stroustrup的入门书,我得到了这段代码:
// simple dictionary: list of sorted words
int main() {
vector<string> words;
for(string temp; cin>>temp;) // read whitespace-separated words
words.push_back(temp); // put into vector
cout << "Number of words: " << words.size() << '\n';
sort(words); // sort the words
for (int i = 0; i < words.size(); ++i)
if (i == 0 || words[i–1] != words[i]) // is this a new word?
cout << words[i] << '\n';
}
我复制了自己:
int main() {
//variables.
vector<string> dictionary;
//prompts user to input words.
cout << "input words in the dictionary:" << endl;
while (dictionary.size() < 10) {
for (string word; cin >> word;) {
dictionary.push_back(word);
}
}
//prints out number of words in the dictionary.
cout << "number of words in the dictionary:" << dictionary.size() << endl;
//sort the words and prints them out one by one, checking for repetitions.
sort(dictionary.begin(), dictionary.end());
for (int i = 0; i < dictionary.size(); ++i)
if ((i == 0) || (dictionary[i-1] != dictionary[i]))
cout << dictionary[i] << '\t';
return 0;
}
但是这里有问题,我无法退出在字典中插入单词的初始循环(我添加的while循环是尝试修复它,但它似乎也不起作用)。
感谢您的时间 :)。
内部for循环将一直运行,直到cin >> word
为false
,如果你继续添加有效字符串可能不是这种情况。此外,你不需要额外的包装for-loop
。您可以执行以下操作,或在必要时添加break
语句。
for (string word; cin >> word && dictionary.size() <10;) {
dictionary.push_back(word);
}