由于获取功能,scanf 无法正确读取 [英] scanf not reading properly because of gets function

查看:65
本文介绍了由于获取功能,scanf 无法正确读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(){
    int n=1,i,cont;
    char string[50];

    scanf("%d",&n);
    while(n!=0){
        gets(string);
        cont=0;
        for(i=0;i<strlen(string);i++){
            if(string[i]=='.'){
                cont++;
            }
        }
        if(cont%2==0){
            printf("S\n");
        }else{
            printf("N\n");
        }
        scanf("%d",&n);
    }
    return 0;
}

我的问题很简单但是很麻烦,我想读取一个整数值n,然后读取一个字符串,然后再读取n,但是每当我运行程序时,它只读取字符串值...但是如果我数字 0 程序结束...就像我的 scanf 在 get 函数中一样.

My problem is quite simple but troublesome, I want to read an integer value n, and then read a string, after that read n again, but whenever I run the program, it only reads the string value... but if I digit 0 the program ends... it's like my scanf is within the gets function.

推荐答案

例如,当您输入 5 时,之后您会遇到一个换行符.所以你要输入 2 个字符:5 和一个换行符.那个换行符让你头疼.

When you enter 5 for an example, you hit a new line character afterwards. So you are entering 2 characters: 5 and a new line character. That new line character is causing your headache.

换行符也被视为输入.

为了忽略这个新行字符,只需添加一个充当垃圾收集的新行:

In order to ignore this new line char, simply add a new line that acts as a garbage collection:

 char garbage[50];

 scanf( "%d", &n);
 fgets(garbage, sizeof(garbage), stdin);

这篇关于由于获取功能,scanf 无法正确读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆