c++ - 谁能告诉我我的代码有什么问题?

标签 c++ c++11

我是编程和 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/

相关文章:

c - 如何使用ZeroMQ实现多个套接字?

c++ - 使用 std::unique_ptr 时 Qt Widget 不显示

c++ - C++11 的垃圾收集 ABI 有实际用途吗?

c++ - C++中涉及多继承和复合类的解决设计

C++ lambda 表达式 : captured pointer to STL container changing address after pop?

c++ - std::vector<bool> resize() 的未定义行为

c++ - 翻转 std::pair 的顺序

c++ - 卡塔琳娜 C++ : Using <cmath> headers yield error: no member named 'signbit' in the global namespace

c++ - "Can' t 解析构造函数"在类中使用类型别名时

c++ - OpenCV 非常慢 - 网络摄像头