Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

c - scanf not reading properly because of gets function

#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
");
        }else{
            printf("N
");
        }
        scanf("%d",&n);
    }
    return 0;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Mixing scanf with gets or fgets is troublesome because they each handle newlines differently.

Get rid of the gets call (which is unsafe anyway) and replace it with the following scanf call:

scanf("%49s", string);

This will read at most 49 characters into string (i.e. one less that its size).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...