忽略整数scanf以外的所有内容
我想将一个整数数组作为输入。 即使有人进入空间或alpahabet,我也想忽略它。
int i=0; while(L--){ scanf("%d",&arr[i++]); }
但是如果我输入: 4 wtf , arr[0]
初始化为4并且循环结束。 有没有办法可以在scanf
的空格之后忽略所有内容并且只取整数。 输入可以是以下forms: 4 abc 3 def 7 ghi 。
我想是这样的吗?
int a; scanf("%d %*s", &a); printf("%d\n",a);
和
input: 11 wwwww output: 11
*
用于跳过输入而不将其放在任何变量中。
试试这个
while(L--){ scanf("%d",&arr[i++]); while(getchar() != '\n'); // Consumes all characters after space. }
您可以使用fgets
从stdin
获取输入字符串,然后使用sscanf
从输入字符串中过滤掉整数。
char input[50]; int num; fgets(input, 50, stdin); sscanf(input, "%d %*s", &num);
遇到整数后, %*s
拒绝字符串。
我认为你在这里想要实现的是从随机输入中提取所有数字。 我建议使用fgets
将输入读入缓冲区,然后使用isdigit
和strtol
提取数字:
#include int main(void) { char buff[255] = {0}; fgets(buff, sizeof(buff), stdin); // read data from stdin char *ptr = buff; do { if(!isdigit(*ptr)) // check if current character is a digit continue; // if not... long val = strtol(ptr, &ptr, 10); // read a number printf("%ld\n", val); // print it } while(*ptr++); // ...move to next character }
……和快速测试:
[root@dmudms01 temp]# ./a.out 1abc23 **4 1 23 4