<span style="font-size:10px;">#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXCHAR 10
void arithmetic(const char *pInputStr, long lInputLen, char *pOutputStr)
{
int i, cnt = 0, a, b, result;
char ch[1] = {'0'};
char op1[MAXCHAR], op[MAXCHAR], op2[MAXCHAR], buffer[4];
for(i = 0; i < lInputLen; i++)
if(pInputStr[i] == ' ')
cnt++;
if(cnt != 2) //空格数不等于2
{
strcat(pOutputStr, ch);
return;
}
sscanf(pInputStr, "%s %s %s", op1, op, op2);
if(strlen(op) > 1 || (op[0] != '+' && op[0] != '-'))
{
strcat(pOutputStr, ch);
return;
}
for(i = 0; i < strlen(op1); i++)
{
if(op1[i] < '0' || op1[i] > '9')
{
strcat(pOutputStr, ch);
return;
}
}
for(i = 0; i < strlen(op2); i++)
{
if(op2[i] < '0' || op2[i] > '9')
{
strcat(pOutputStr, ch);
return;
}
}
a = atoi(op1);
b = atoi(op2);
switch(op[0])
{
case '+':
result = a + b;
itoa(result, buffer, 10);
strcat(pOutputStr, buffer);
break;
case '-':
result = a - b;
itoa(result, buffer, 10);
strcat(pOutputStr, buffer);
break;
default:
break;
}
}
int main()
{
char pInputStr3[] = {"3 + 4"};
char pOutputStr3[MAXCHAR] = {0};
arithmetic(pInputStr3, strlen(pInputStr3), pOutputStr3);
printf(pOutputStr3);
return;
}</span>把一个整数转换为字符串用法itoa(i,num,10);
i ----需要转换成字符串的数字
num---- 转换后保存字符串的变量
10---- 转换数字的基数(即进制)。10就是说按10进制进行转换。还可以是2,8,16等等你喜欢的进制类型
返回值:指向num这个字符串的指针
3.atoi( )用法与iota( )正好相反
参考程序:http://blog.csdn.net/poinsettia/article/details/9569987程序:Output result string after numbers addition and subtraction
原文:http://blog.csdn.net/xinyu913/article/details/42499983