调试断言失败c> = -1&&c< = 255 [英] Debug Assertation Failed c >= -1 && c <= 255
问题描述
用我的代码很难理解这个运行时错误.这是我的课上的作业,我认为这很容易,但还有一些奇怪的事情要做.我已经在下面发布了我的代码.
I am having a difficult time understanding this runtime error with my code. This was an assignment for my class that I thought would be easy, but something strange is gong on. I have posted my code below.
进行此分配的提示是创建一个程序,要求用户输入以输入一些单词,然后应输出有多少个单词.我有一个朋友运行该程序,并且可以正常运行,但是,每当我尝试运行该程序时,都会出现此运行时错误.[ http://imgur.com/FcdN3zK ]
The prompt for this assignment was to create a program that asks the user to enter to enter some words, then it should output how many words there are. I have had a friend run the program and it worked, however, whenever I try to run it I get this runtime error. [ http://imgur.com/FcdN3zK ]
请记住,我一般是C ++和编程的初学者,所以我将无法理解非常技术性的回答.预先感谢您的协助.
Please keep in mind that I am a beginner at C++ and programming in general, so I won't be able to understand very technical responses. Thank you in advance for your assistance.
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
int wordCounter(char *);
int main()
{
char *stringArray = nullptr;
stringArray = new char[120];
cout << "Please enter a saying or a phrase that has more than one word: " << endl;
cin.getline(stringArray, 120);
int words = wordCounter(stringArray);
cout << "Your statement contains " << words << " words." << endl;
system("pause");
return 0;
}
int wordCounter(char *stringTest)
{
char characterToTest;
int numberOfWords = 0;
for (int i=0; i < 120; i++)
{
characterToTest = *(stringTest + i);
if (isspace(characterToTest) && i != 120)
{
char characterToTestTemp = *(stringTest + (i + 1));
if (isalnum(characterToTestTemp))
{
numberOfWords++;
}
}
}
return numberOfWords;
}
推荐答案
isspace
和朋友很难正确地打电话.具体来说,您不能安全地将 char
传递给它们,因为 char
的值可以为负,并且不允许这样做,如错误消息所述.
isspace
and friends are surprisingly hard to call correctly. Specifically you can't safely pass a char
to them, because char
values can be negative and that is not allowed, as the error message says.
为了安全起见,您应该强制转换为 unsigned char
:
You should cast to unsigned char
to be safe:
isspace(static_cast<unsigned char>(characterToTest))
这不是这里的主要问题,您需要首先解决溢出问题,但这是您收到错误消息的原因之一.
That isn't the main problem here, you need to fix the overrun first, but it's part of why you're getting the error message.
这篇关于调试断言失败c> = -1&&c< = 255的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!