本文是小编为大家收集整理的关于程序没有在scanf("%c", &ch)行停止,为什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
程序在SCANF上停止("%C",&CH)线路.为什么它会发生ombody可以请向我解释它
#include<stdlib.h> #include<stdio.h> struct list { char val; struct list * next; }; typedef struct list item; void main() { char ch; int num; printf("Enter [1] if you want to use linked list or [2] for realloc\n"); scanf("%d", &num); if(num == 2) { scanf("%c", &ch); printf("%c", ch); } }
推荐答案
让我们说你在读取num时输入2.实际输入流将是2 \ n(\ n是换行符). 2进入Num,并且仍然存在\ n,进入ch.为避免这种情况,请在格式说明符中添加空格.
scanf(" %c", &ch);
这将忽略任何空格,纽单或标签.
其他推荐答案
背后的原因是ewhine \n字符左后面的scanf,按输入键时,下一个读取scanf.当语句
scanf("%c", &ch);
然后执行它读取的\n留下的前后scanf.
要进食这个\n你可以在%c说明符之前使用空格. %c说明符之前的空间能够进食任何数量的空白空间字符.
scanf(" %c", &ch); ^ a space
问题描述
the program doesnt stop on scanf("%c", &ch) line. why does it happens sombody can please explain this to me
#include<stdlib.h> #include<stdio.h> struct list { char val; struct list * next; }; typedef struct list item; void main() { char ch; int num; printf("Enter [1] if you want to use linked list or [2] for realloc\n"); scanf("%d", &num); if(num == 2) { scanf("%c", &ch); printf("%c", ch); } }
推荐答案
Let's say you input 2 when you're reading for num. The actual input stream will be 2\n (\n is the newline character). 2 goes into the num, and there remains \n, which goes into ch. To avoid this, add a whitespace in format specifier.
scanf(" %c", &ch);
This will ignore any whitespaces, newlines or tabs.
其他推荐答案
The reason behind this is the newline \n character left behind by previous scanf, when pressing Enter key, for the next read of scanf. When the statement
scanf("%c", &ch);
executed then it reads that \n left behind by the previous scanf.
To eat up this \n you can use a space before %c specifier. A space before the %c specifier is able to eat up any number of white-space characters.
scanf(" %c", &ch); ^ a space