I encountered a question today, I think it is very meaningful, so write it down and record it
topic:
This question requires extracting all numeric characters ('0'...'9') in a string and converting it to an integer output.
I didn't read the topic carefully at first, and then my first thought was to find the numeric characters in the string and print them out directly. The code is as follows
#include <stdio.h>
int main()
{
char arr[81];
int len = 0;
//输入字符串,并记录下len
while (1)
{
scanf("%c", &arr[len]);
if (arr[len] == '\n')
{
break;
}
len++;
}
//我当时就是直接找出数字字符,然后直接打印出来
for(int i = 0;i < len;++i)
{
if(arr[i] >= '0' && arr[i] <= '9')
{
printf("%c", arr[i]);
}
}
return 0;
}
When I submitted it later, I found out that it needs to be converted into an integer output.
The improved code is as follows
#include<stdio.h>
int main()
{
char arr[80];
char b[80];
int n = 0;
int len = 0;
while (1)
{
scanf("%c", &arr[len]);
if (arr[len] == '\n')
{
break;
}
len++;
}
将数字备份到字符串b中
for (int i = 0; i < len; ++i)
{
if (arr[i] >= '0' && arr[i] <= '9')
{
b[n] = arr[i];
n++;//记录b的个数
}
}
int sum = 0;
//最大的坑
//本题要求提取一个字符串中的所有数字字符('0'……'9'),将其转换为一个整数输出。
for (int i = 0; i < n; ++i)
{
//输出最好按题目要求
if (i == 0)
{
sum = b[i] - '0';
}
//字符串转数字要-'0'
else
{
sum = sum * 10 + b[i] - '0';
}
}
printf("%d", sum);
}
Finally, make a small summary.
In fact, this question is not that difficult, it is very basic. However, due to my sloppyness, I did not write according to the requirements of the topic, which caused me to spend a certain amount of time.
So, veterans, you still have to read the questions carefully, and don’t make such low-level mistakes like me.