C语言编写,输入一行字符(用回车结束),每个数字字符的前后都有空格.请编程,把这一行中的数字转换成一个整数

例如,若输入(<CR>代表Enter键):
2 4 8 3 <CR>
则输出整数:2483.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void main(){
char s[255], *t = s, *start = s;
int find_digit = 0;
long num = 0;
printf("Please input a strings(include digits): "); /* 请输入 1 个含有数字的字符串 */
gets(s);
printf("\n");
while (*t != '\0'){
if (isdigit(*t)){
if (!find_digit) start = t;
find_digit = 1;
t++;}
else if (*t == ' ') strcpy(t, t + 1); /* 删除空格 */
else if (find_digit){
*t = '\0';
break; }
else t++;
}
if (!find_digit)
printf("NO any digit in the string!\n");
else{
printf("The digit form in the string is %s\n", start); /* 字符串里的数字部分 */
/* 字符串里的数字部分转换为真正的整数 */
while (*start != '\0'){
num *= 10;
num += (int)(*start - '0');
start++;
}
printf("The number from string is %ld\n", num); /* 输出真正的整数 */
}
printf("Press any key to continue...\n");
getch();
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2019-05-05
#include<stdio.h>
main()
{
char c;
while((c=getchar())!='\n')
{
if(c>='0'&&c<='9')
{
c-='0';
printf("%d",c);
}
}
putchar('\n');
}
第2个回答  推荐于2018-04-18
//---------------------------------------------------------------------------

#include <stdio.h>
#include <ctype.h>

int main(int argc, char* argv[])
{
char a;
int i=0;
while ((a=getchar())!='\n')
if (isdigit(a)) i=i*10+a-48;
printf("%d",i);
return 0;
}
//---------------------------------------------------------------------------本回答被提问者和网友采纳