C++ C++;调试断言失败的字符串数组
我正在为我的课程编写一个作业,其中一个用户将输入10个字母的答案,程序将返回一个分数。我最近把我的字符数组改成了字符串数组,因为我认为这样更容易阅读。 我去调试我的代码,现在得到了错误“Deubug断言失败”。我不知道这意味着什么,也不知道如何修复它 任何帮助都将不胜感激。 谢谢 下面是我的代码:C++ C++;调试断言失败的字符串数组,c++,string,C++,String,我正在为我的课程编写一个作业,其中一个用户将输入10个字母的答案,程序将返回一个分数。我最近把我的字符数组改成了字符串数组,因为我认为这样更容易阅读。 我去调试我的代码,现在得到了错误“Deubug断言失败”。我不知道这意味着什么,也不知道如何修复它 任何帮助都将不胜感激。 谢谢 下面是我的代码: // Lab 8 // programmed by Elijah Barron #include <iostream> #include <string> #include
// 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;
}
//实验8
//以利亚·巴伦编剧
#包括
#包括
#包括
使用名称空间std;
//函数头
字符串输入应答器(给定字符串);
int numCorrect(字符串更正,字符串给定);
int main()
{
字符串correctAnswers=“BCADBADCAB”;
给定字符串;
int numRight=0;
输入应答器(给定);
numCorrect(正确答案,已给出);
双级=10*numRight;
不能您想在向量中保留足够的空间来容纳10个字符,或者使用向后推
来填充向量。使用[]
索引向量不会增加向量
编辑:
忽略关于reserve
的第一部分。这不会停止调试断言。您需要更改此设置
cin >> given[n];
对这样的事情:
char input;
cin >> input;
given.push_back(input);
当前的问题是,给定的将以空字符串开始,因为您尚未为其赋值:
cin >> given[n];
正在导致断言失败,因为您试图更改长度为零的字符串中的第一个(第二个、第三个等)字符。若要解决断言问题(但不是程序,它将始终返回0%),只需初始化字符串:
string given = "ZZZZZZZZZZ";
要解决其余问题(顺便说一句,这不是唯一的方法):
更改:
string inputAnswers(string given); //for both prototype and function.
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;
}
致:
更改:
string inputAnswers(string given); //for both prototype and function.
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;
}
和变化:
numCorrect(correctAnswers, given);
致:
这个分号捕捉得很好,但是由于for循环中声明的n
在同一分号处超出范围,下面括号中的代码使用循环上方声明的另一个n
。该n
仍将设置为零。
numCorrect(correctAnswers, given);
int numRight = numCorrect(correctAnswers, given); //declared when necessary and assigned the correct value