scanf无法按预期工作

3

我尝试在Ubuntu 15.10中执行以下简单代码,但代码的行为与预期不同。

#include<stdio.h>
int main(){
int n,i=0;
char val;
char a[20];

printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%c",&val);

int count=0;
for(i=0;i<20;i++){
 if(a[i]==val){
   printf("\n%c found at location %d",val,i);
   count++;
 }
}
printf("\nTotal occurance of %c is %d",val,count);
   return 0;
}

output:
--------------------------
Enter the value : 12345678
Enter the value to be searched : 
Total occurance of is 0

第二个scanf获取要搜索的值似乎没有起作用。在第一个scanf之后,代码的其余部分执行而未获得第二次输入。

1
  1. scanf("%c",&val); --> scanf(" %c",&val);
  2. i<20 --> i<20 && a[i]
  3. scanf("%s",a); --> scanf("%19s", a); (i<20 --> ia[i])
- BLUEPIXY
ia[i]我的打字错误为a[i] - BLUEPIXY
为什么不检查 scanf 的返回值?同时确保它不会越界数组。 - Ed Heal
如果你在SO上因此而痛苦呼号,那么scanf()正按预期工作。 - 15ee8f99-57ff-4f92-890c-b56153
%c 接受 '\n',12345678(回车)-> 12345678'\n' - KunMing Xie
4个回答

1
在第一个scanf()之后,在每个scanf()中的格式化部分,加上一个空格。
因此,将其更改为:
scanf("%c",&val);

转换为这个

scanf(" %c",&val);

原因是,scanf()在看到换行符时返回,当第一个scanf()运行时,您输入并按回车键。 scanf()消耗了您的输入,但未消耗剩余的换行符,因此,接下来的scanf()会消耗这个剩余的换行符。
在格式化部分放置一个空格可以消耗掉剩余的换行符。

0
你可以使用 fgets()
#include<stdio.h>
int main() {
    int n, i = 0;
    char val;
    char a[20];

    printf("\nEnter the value : ");
    fgets(a, 20, stdin);
    printf("\nEnter the value to be searched : ");
    scanf("%c", &val);

    int count = 0;
    for (i = 0; i < 20; i++) {
        if (a[i] == val) {
            printf("\n%c found at location %d", val, i);
            count++;
        }
    }
    printf("\nTotal occurance of %c is %d", val, count);
    return 0;
}

或清除 stdin

#include<stdio.h>

void clearstdin(void) {
    int c;
    while ((c = fgetc(stdin)) != EOF && c != '\n');
}

int main() {
    int n, i = 0;
    char val;
    char a[20];

    printf("\nEnter the value : ");
    scanf("%s",a);
    clearstdin();
    printf("\nEnter the value to be searched : ");
    scanf("%c", &val);

    int count = 0;
    for (i = 0; i < 20; i++) {
        if (a[i] == val) {
            printf("\n%c found at location %d", val, i);
            count++;
        }
    }
    printf("\nTotal occurance of %c is %d", val, count);
    return 0;
}

此外,还可以查看C语言:多个scanf函数的情况下,当我为一个scanf输入值时,它会跳过第二个scanf函数


0
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%d",&val);   // here is different

我不知道为什么,但是上面的代码可行...

scanf("%d",&val);

1
scanf函数会清除空格,但当使用字符格式(%c)时除外。在OP的示例中,输入“12345678”并按回车键意味着a获取“12345678”,而stdin缓冲区中有一个换行符('\n')字符。%d会将其删除,但%c不会。 - orestisf

0

在格式字符串中,您可以使用“%c”代替“%c”。空格会导致scanf()在读取字符之前跳过空格(包括换行符)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接