题目:输入一个表示整数的字符串,把该字符串转换成整数并输出
例如,输入字符串“123”,则输出整数123,输入字符串“-456”,则输出整数-456,输入字符串“a123”,则输出 illegal number
#include<stdio.h> #include<stdlib.h> int strtoint(char* str) { int neg=1; char* p = str; if(*p == '-') { p++; neg = -1; } else if(*p == '+') { p++; } int num=0; while(*p!='\0') { if(*p>='0' && *p<='9') { num = num*10+(*p-'0'); } else { printf("illegal number\n"); exit(1); } p++; } return num*neg; } int main() { printf("Enter a string:"); char str[50]; scanf("%s",str); int result = strtoint(str); printf("%d\n",result); }