我正在提示用户输入数组的长度,用此输入初始化一个char[]数组,然后提示用户输入要输入到char[]数组中的消息。
我使用
但是,在读取任何用户输入之前,
以下是相关代码:
我使用
getchar()
读取用户消息的第一个字符。但是,在读取任何用户输入之前,
getchar()
会读取新行转义符'\n'
。它似乎是从上一个printf
语句中获取了'\n'
,该语句提示用户...以下是相关代码:
#include <stdio.h>
int main(void) {
int len = 0,
originalLen = 0;
printf("\n\nWhat is the length of the array? ");
scanf("%d", &originalLen);
char str[originalLen]; // intitializing the array
printf("Enter a message to enter into the array: ");
char target = getchar();
str[len] = target;
// why is getchar() reading '\n'?
if (target == '\n') {
printf("\n...what happened?\n");
}
return 0;
} // end of main
scanf
读取(并丢弃)空格。至于“专业接受”,我自己经常使用它,并在许多其他代码中看到它,所以它并不罕见。 - Some programmer dude