C语言使用scanf函数获取数据后,使用getchar()无法获得字符的处理方法
int main(){
42 char str[N];
43 char ch;
44 printf("String input(len<%d):",N);
45 scanf("%s",str);
47 printf("\noutput to a TXT file?[Y/N]\n");
48 ch=getchar();
49
50 if(ch=='Y' | ch=='y')
51 if((fp=fopen("HA_output.txt","w"))==NULL){
52 puts("FILE OPEN ERROR!");
53 getchar();
54 return 1;
55 }
56 /* if end */
57
58 Permutation(str,0,strlen(str));
59
60 printf("\nSum=%d",count);
61 if(fp!=NULL){
62 printf("\ndata is written in the \"HA_output.txt\" ");
63 fclose(fp);
64 }---
65 getchar();
66 }
45行使用scanf后,48行getchar无法获得字符;
使用dgb调试信息:
(gdb) display ch
1: ch = 0 '\000'
(gdb)
(gdb) s
45 scanf("%s",str);
1: ch = 0 '\000'
(gdb) display str
2: str = "\000\364\017,\000Ї\004\b\300\204\004\bۇ\004\b\364\017,"
(gdb) s
String input(len<20):121
46 printf("\noutput to a TXT file?[Y/N]\n");
2: str = "121\000\000Ї\004\b\300\204\004\bۇ\004\b\364\017,"
1: ch = 0 '\000'
(gdb) s
output to a TXT file?[Y/N]
47 ch=getchar();
2: str = "121\000\000Ї\004\b\300\204\004\bۇ\004\b\364\017,"
1: ch = 0 '\000'
(gdb) s
49 if(ch=='Y' | ch=='y')
2: str = "121\000\000Ї\004\b\300\204\004\bۇ\004\b\364\017,"
1: ch = 10 '\n'
(gdb) print ch
$1 = 10 '\n'
字符ch直接赋值为'\n';
getchar读取上次输入的最后回车符,导致getchar不起作用;
处理方法:
45 scanf("%s",str);
46 getchar();
在scanf下直接调用getchar获取回车符;
下次再使用getchar就不受影响了。