C 运行时错误:调试断言失败
我正在编写一个计算器,它在cmd上工作。我主要完成了+、-、/、*操作和两个数字,但我有这个错误。我查找了这个错误,但是所有的文档都是关于文件函数的。我不使用file func。但我还是犯了这个错误: 调试断言失败! 课程:…所有学习2012。。。。 文件:f:\dd\vctools\crt\u bld\self\u x86\crt\srt\strtol.c 电话号码:94 表达方式:nptr=空的 代码为:C 运行时错误:调试断言失败,c,visual-studio-2012,C,Visual Studio 2012,我正在编写一个计算器,它在cmd上工作。我主要完成了+、-、/、*操作和两个数字,但我有这个错误。我查找了这个错误,但是所有的文档都是关于文件函数的。我不使用file func。但我还是犯了这个错误: 调试断言失败! 课程:…所有学习2012。。。。 文件:f:\dd\vctools\crt\u bld\self\u x86\crt\srt\strtol.c 电话号码:94 表达方式:nptr=空的 代码为: #include <stdio.h> #include <strin
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char define(char input[]);
float math(int sayi[], char operation);
void main()
{
int sayi[100];
char input[100];
char inputCpy[100];
const char functions[] = "+,-,/,*";
char *token;
char operation;
float result;
int i=1;
printf("welcome to my simple cmd calculator!\n what do you want to know?\n");
scanf("%s", input);
strcpy(inputCpy,input);
token = strtok(input, functions);
sayi[0]=atoi(token);
while( token != NULL )
{
token = strtok(NULL, functions);
sayi[i]=atoi(token);
i++;
}
printf ("sayi1=%d sayi2=%d", sayi[0], sayi[1]);
operation = define(inputCpy);
printf("operation = %c\n", operation);
result = math(sayi,operation);
printf ("result = %.2f\n", result);
system("pause");
}
char define(char input[])
{
char operation;
for (int i=0; i<strlen(input); i++)
{
if(!isdigit(input[i]))
{
operation = input[i];
break;
}
}
return operation;
}
float math(int sayi[], char operation)
{
float result=0;
switch(operation)
{
case '+':
result = sayi[0]+sayi[1];
break;
case '-':
result = sayi[0]-sayi[1];
break;
case '*':
result = sayi[0]*sayi[1];
break;
case '/':
if(sayi[1]!='0')
{
result = sayi[0]/sayi[1];
}
else
{
printf ("wtf!! you can't divide by 0!");
}
break;
default:
printf("did you mean \"i don't know maths\"");
}
return result;
}
您需要检查strtok的返回值,否则可能会向atoi传递空指针。稍后在代码中使用相同的token=strtokNULL,函数 在调用atoitoken之前,需要检查令牌是否为NULL
更改行:
token = strtok(input, functions);
sayi[0]=atoi(token);
while( token != NULL )
{
token = strtok(NULL, functions);
sayi[i]=atoi(token); // token will eventually be NULL
// and you run into a problem here.
i++;
}
致:
笔划返回字符串,不是吗?我应该检查什么?你的意思是:如果strtokinput,函数=空?@osumatu检查strtok的手册页,如果strtok找不到令牌怎么办?谢谢,它工作了,但仍然有问题。我得到的数字[0]是正确的,但数字[1]是错误的。为什么?@osumatu,您可以添加行来打印令牌,并在while循环中说i[i]来诊断问题。
token = strtok(input, functions);
sayi[0]=atoi(token);
while( token != NULL )
{
token = strtok(NULL, functions);
sayi[i]=atoi(token); // token will eventually be NULL
// and you run into a problem here.
i++;
}
token = strtok(input, functions);
i = 0;
while( token != NULL )
{
sayi[i]=atoi(token);
token = strtok(NULL, functions);
i++;
}