gpt4 book ai didi

C++ 调试断言失败的字符串数组

转载 作者:行者123 更新时间:2023-11-28 06:33:37 25 4
gpt4 key购买 nike

我正在为我的类(class)编写作业,用户将输入 10 个字母的答案,程序将返回成绩。我最近将我的字符数组更改为字符串数组,因为我认为它更易于阅读。我去调试我的代码,现在收到错误“Deubug Assertion Failed”。我不知道这意味着什么或如何解决它。

如有任何帮助,我们将不胜感激。谢谢!

下面是我的代码:

// Lab 8
// programmed by Elijah Barron

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;


//Function headers
string inputAnswers(string given);
int numCorrect(string correctAnswers, string given);

int main()
{
string correctAnswers = "BCADBADCAB";
string given;
int numRight = 0;

inputAnswers(given);

numCorrect(correctAnswers, given);

double grade = 10 * numRight;

cout << "Your quiz grade is " << grade << "%" << endl;

return 0;
}
//Get the answers


string inputAnswers(string given)
{
for (int n = 0; n < 10; n++)
{
cout << "Please enter your answer for question #" << n + 1 << " ";
cin >> given[n];
}
return given;
}

//Find if answers are correct or incorrect

int numCorrect(string correctAnswers, string given)
{
int numRight = 10;
int n = 0;
for (int n = 0; n < 10; n++);
{
if (given[n] != correctAnswers[n])
numRight -= 1;
}

return numRight;
}

最佳答案

直接的问题是 given 将以空字符串开始,因为您尚未为其分配值:

cin >> given[n];

导致断言失败,因为您试图更改长度为零的字符串中的第一个(第二个、第三个等)字符。要解决断言问题(但不是程序,它将始终返回 0%),只需初始化字符串:

string given = "ZZZZZZZZZZ";


要修复其余的东西(顺便说一句,这不是唯一的方法):

改变:

string inputAnswers(string given); //for both prototype and function.

到:

void inputAnswers(string& given); //pass by reference instead of pass by value.
//also get rid of "return given;"

改变:

int n = 0; //the n here is different to the one in the next line
for (int n = 0; n < 10; n++); //this n's scope begins and ends here thanks to the semicolon
{//the code here is executed once, this isn't in the loop!
if (given[n] != correctAnswers[n]) //we're using the first n here, which is 0.
numRight -= 1;
}

到:

for (int n = 0; n < 10; n++) //only one n variable and no semicolon
{// now this is in the loop and will execute 10 times.
if (given[n] != correctAnswers[n])
numRight -= 1;
}

不要理会这一行:

int numRight = 0; //Set at 0 and then never changed.

和改变:

numCorrect(correctAnswers, given);

到:

int numRight = numCorrect(correctAnswers, given); //declared when necessary and assigned the correct value

关于C++ 调试断言失败的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com