C Noob question: scanf("%s") leaves trash in stdin

sorry, I know this is kind of a standart question but:

1
2
3
4
5
6
7
 char *filename[80];
 char filetype;

 printf("filname?\n");
 scanf("%s",filename);
 printf("type? (b/k)\n");
 scanf("%c",&filetype);


the first scanf will always leave some crap that makes the other scanf useless.

I read something about using fflush(sdtin), but I also read that that was undefined and should not be used as the behavior of fflush is im,plementation dependent, when used on stdin.

I can't realy get that runing right now =(

pls help a noob thy
Last edited on
char *filename[80];

creates an array of 80 pointers-to-char, which is certainly not what scanf is expecting when you tell it via %s that filename is an array of char.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

int main()
{

    char filename[80];
    char filetype;

    printf("file name?\n");
    scanf("%s", filename);

    printf("type? (b/k)\n");
    scanf(" %c", &filetype);  /* skip leading whitespace */

    printf("filename: \"%s\" \t filetype: \"%c\"\n", filename, filetype);
}
Last edited on
+1 for the space before %c.
to make that even better, scanf("%79s", filename);, otherwise this program is begging to be hacked
Last edited on
the char *[80] was a result of me wanting to malloc first and then decied to change that. thanks for spoting that ^^
Topic archived. No new replies allowed.