我是编程和 C++ 的新手。如果这听起来很愚蠢,那么您就知道为什么了。 我的代码有问题。出于某种原因,当我创建一个函数来实现这一点时,并非所有具有 4 个字母的字符串都不会进入我的数组。加, 具有 6 个字母的字符串也会进入我的数组,这些字符串应该只存储在 4 个或用户想要放置的任何内容中。
我已经尝试了很多,我什至无法列出它们。
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
string LetterInput, LetterLoad, input;
string Words[] = {"camera","lotion","fire","eggs","roll"};
string PossibleAnswers[] = {};
int Number;
int Size;
bool YesorNo = false;
cout << "Lets play HANGMAN! " << endl;
Sleep(500);
cout << "Think of a word and type in the number" << endl;
cout << "of letters there are" << endl;
cin >> Size;
for (int i = 1; i <= Size; i++){
LetterLoad += "_";
}
for (int i = 0; i <= sizeof(Words)/sizeof(string); i++){
if (Size == Words[i].size()){
PossibleAnswers[i] = Words[i];
}
}
cout << PossibleAnswers[0] << endl;
cout << PossibleAnswers[1] << endl;
我的预期结果是数组仅按顺序显示 "fire","eggs","rolls"
。但实际结果是,"camera","lotion","fire","eggs"
。大声笑,这是什么问题。
最佳答案
这是对您的代码的更正。如评论中所述,执行此操作的简单方法是使用 std::vector
而不是数组。在 C++ 中应避免使用数组(一般而言)。
#include <vector>
...
vector<string> Words{"camera","lotion","fire","eggs","roll"};
vector<string> PossibleAnswers;
...
for (size_t i = 0; i < Words.size(); i++){
if (Size == Words[i].size()){
PossibleAnswers.push_back(Words[i]);
}
}
请注意使用 push_back
将项目添加到 vector 中。这是你不能用数组做的事情,因为数组总是固定大小的。这是你的基本错误。
关于c++ - 谁能告诉我我的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405658/