Using scanf and fgets in one program?

I need to do something like the following:

int main(void) {
char a,b,cstring;

printf("please enter something");
scanf("%c %c",&a,&b);
prinf("thanks, now some more");
fgets(cstring,35,stdin);

}

The problem is that whenever I enter the first vars from scanf, it skips to the end of the program. How to make multiple entries?

+5
source share
4 answers

The first problem is that it scanf()reads two characters, but not after a new line.

This means your fgets()reads a new line and finishes.

, . fgets(), 35 , ( , ). , , #include <stdio.h> ( scanf() C scanf() ), , , .

. , GCC 4.6.0 :

/usr/bin/gcc -g -I/Users/jleffler/inc -std=c99 -Wall -Wextra -Wmissing-prototypes \
     -Wstrict-prototypes -Wold-style-definition xxx.c
xxx.c: In function ‘main’:
xxx.c:7: warning: implicit declaration of function ‘prinf’
xxx.c:8: warning: passing argument 1 of ‘fgets’ makes pointer from integer without a cast

, , prinf() printf(), , , : " , prinf()!".

, .


:

?

scanf() ; , , fgets() . - , scanf() ( sscanf()). :

#include <stdio.h>
int main(void)
{
    char a,b,cstring[35];

    printf("please enter something");
    scanf("%c %c%*c", &a, &b);
    printf("thanks, now some more");
    fgets(cstring, 35, stdin);
    printf("OK: I got %c and %c and <<%s>>\n", a, b, cstring);
    return 0;
}

%*c ( ), ( - *). , , . , , :

#include <stdio.h>
int main(void)
{
    char a,b,cstring[35];
    int c;

    printf("please enter something");
    scanf("%c %c", &a, &b);
    while ((c = getchar()) != EOF && c != '\n')
        ;
    printf("thanks, now some more");
    fgets(cstring, 35, stdin);
    printf("OK: I got %c and %c and <<%s>>\n", a, b, cstring);
    return 0;
}

, getchar() int, char. . , , , - .

+7

undefined. cstring, , , 35 , . , cstring , . ( ) 0 255 .

. - :

#include <stdio.h>
int main(void) {
    char a,b,cstring[99];

    printf("please enter something");
    scanf("%c %c",&a,&b);
    printf("thanks, now some more");
    fgets(cstring,35,stdin);

    return 0;
}

, , :

#include <stdio.h>
int main(void) {
    char a,b,cstring[99];

    printf("please enter something");
    fgets(cstring,35,stdin);
    sscanf(cstring,"%c %c",&a,&b);
    printf("thanks, now some more");
    fgets(cstring,35,stdin);

    return 0;
}

, , . . .

+1

, fgets(), API stdin , "\n". fgets(), , API , EOF '\n', fgets() '\n' stdin, , , - , , API .

, getchar(); scanf , scanf(). :

scanf("%lf",&e);
getchar();
fgets(t,200,stdin);

sscanf fgets. :

#include <stdio.h>
int main() {
int j;char t[200];
fgets(t,200,stdin);
sscanf(t,"%d",&j);
}
0

fflush (stdin) scanf,

-1
source

All Articles