Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf and fgets in the same program?

Tags:

c

scanf

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);

}

Problem is that whenever I enter the first vars from scanf, it skips to the end of the program. How do I do multiple inputs?

like image 278
wesbos Avatar asked Apr 05 '11 03:04

wesbos


People also ask

How do I use fgets after scanf?

How do I make Fgets work after scanf? This can be solved by introducing a “\n” in scanf() as in scanf("%d\n", &x) or by adding getchar() after scanf().

Can we use scanf and gets in same program?

No. The scanf() function can read input from keyboard and stores them according to the given format specifier. It reads the input till encountering a whitespace, newline or EOF. On other hand gets() function is used to receive input from the keyboard till it encounters a newline or EOF.

What is the problem of using scanf () function?

Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program. 2) The similar problem occurs when scanf() is used in a loop.

Can you use fgets on Stdin?

Since fgets() reads input from user, we need to provide input during runtime. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.


2 Answers

The first problem is that the scanf() reads two characters, but not the newline afterwards.

That means your fgets() reads the newline and finishes.

You are lucky your program is not crashing. You tell fgets() that it is getting an array of 35 characters, but rather than passing an array, you pass the character (not the address of a character, even). That also tells us you are not including #include <stdio.h> (you can't use scanf() reliably according to the C standard without a prototype for scanf() in scope), and you are not compiling with enough warnings enabled, or not paying enough attention to what your compiler is telling you.

You should be getting compiler warnings. For example, GCC 4.6.0 says:

/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

And, darn it, I hadn't even noticed the spelling mistake of prinf() for printf() until I tried linking and the compiler rubbed my nose in it by saying "Don't know what prinf() is!".

If your compiler doesn't at least give the second warning, get yourself a better compiler.


Comment:

How do I stop it from reading the newline after it?

The problem is not stopping the scanf() from reading the newline; the problem is actually how to make it read it so that fgets() gets a clear run at the next line of input. It actually is modestly tricky - one reason why I seldom use scanf() (but I often use sscanf()). This does the job for simple inputs:

#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;
}

The %*c reads an extra character (a newline) without assigning it anywhere (that's because of the *). However, if there are multiple characters after the second non-blank, it is no help. I'd probably write a loop to read to the newline:

#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;
}

Note that getchar() returns an int and not a char. This reliably discards everything on the first line of input. It also shows how to echo what you read - an important part of debugging.

like image 98
Jonathan Leffler Avatar answered Oct 02 '22 06:10

Jonathan Leffler


That's undefined behaviour. Your cstring variable, despite its name, is a single character, and you are attempting to read up to 35 characters into what its current value points to. In other words, the current character in cstring will be converted into a pointer and it will try to write your input there. That's going to be a memory location (most likely) between 0 and 255 inclusive.

That's what's causing your segmentation violation. Start with something like this instead:

#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;
}

Or, possibly better:

#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;
}

Or, if you want a more robust solution for user input, see here. It's a tried and tested method with very good error checking.

like image 31
paxdiablo Avatar answered Oct 02 '22 05:10

paxdiablo