谁能告诉我我的代码出了什么问题

Can anyone tell me whats wrong with my code?

本文关键字:什么 问题 代码 告诉我 我的      更新时间:2023-10-16

我是编程和 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 将项添加到矢量。这是你不能用数组做的事情,因为数组总是固定大小的。这是你的基本错误。

您有多个问题。其中大多数是因为您的旧式C++代码。始终使用最新的可用标准,在您的情况下可能是C++14甚至C++17。

简而言之:使用std::vector

始终避免使用原始数组。改用标准库的容器类,它们会让你的生活更轻松。在这种情况下,std::vector应该是您的选择,因为它是一个易于使用且动态分配(可调整大小)的数组。

std::vector<std::string> words {"camera","lotion","fire","eggs","roll"};
std::vector<std::string> possible_answers;

目前,您使用空数组 PossibleAnswers,这意味着您内部没有元素。但是 - 您尝试使用这些元素。相反,请尝试以下操作:

for(i = 0; i < words.size(); ++i)
    if(size_input == words[i].size())
        possible_answers.push_back(words[i]);

您必须使用#include <vector>才能使用向量。

我更喜欢std::this_thread::sleep_for(std::chrono::milliseconds(500))而不是Sleep(500)。如果标准中有替代方案,请尽量避免使用特定于平台的功能。为了能够使用它,请包含标头<thread>