【发布时间】:2010-02-20 19:37:18
【问题描述】:
当我在 C++ 中使用以下代码时,我得到一个无限循环,我不明白为什么。我怀疑问题出在input_words() 函数中。代码如下:
#include<iostream>
using namespace std;
string input_words(int maxWords) {
int nWord = 0;
string words[maxWords];
string aWord = "";
while (aWord != "Quit" && nWord < maxWords) {
cout << "Enter a number ('Quit' to stop): ";
getline (cin, aWord);
words[nWord] = aWord;
nWord++;
}
return *words;
}
int num_words (string words[], int maxWords) {
int numWords = 0;
for (int i=0; i<maxWords; i++) {
if (words[i] == "Quit") {
break;
}
numWords++;
}
return numWords;
}
int main() {
const int MAX_WORDS = 100;
string words[MAX_WORDS] = input_words(MAX_WORDS);
int lenWords = num_words(words, MAX_WORDS);
cout << "\nThere are " << lenWords << " words:\n";
for (int i=0; i<MAX_WORDS; i++) {
if (words[i] == "Quit") {
break;
}
cout << words[i] << "\n";
}
return 0;
}
更具体地说,即使在提示输入单词时键入“退出”,我也无法退出。我怎么能解决这个问题?我知道这是菜鸟代码 :) 我刚刚开始使用 C++
【问题讨论】:
-
这应该可以正常工作。此外,这是一个扩展,而不是 C++:
string words[maxWords];在 C++ 中,数组具有恒定大小。如果你想要一个动态数组,你应该使用std::vector<std::string>,并使用push_back添加东西。这也消除了您对最大尺寸的需求。最后,这个:return *words;将只返回第一个字符串。也许您的意图是返回整个数组,在这种情况下,将返回类型设为std::vector<std::string>并返回向量。 -
@GMan:afaik g++ 支持堆栈上动态大小的数组,但请注意这不符合标准。
-
非常感谢 GMan!我觉得你应该发布(或发布)这个作为答案。在阅读您的评论之前,我刚刚发布了一个关于声明向量的新问题。我还认为向量是要走的路,但我没有成功声明它。
-
@JP:因此 GMan 将其称为扩展,即标准未定义的附加功能。
-
@JPvdMerwe:这个 g++ 问题将如何影响特定问题?
标签: c++ function user-input infinite-loop