我想阅读用户使用C程序输入的名称.
为此,我写道:
char name[20];
printf("Enter name: ");
gets(name);
Run Code Online (Sandbox Code Playgroud)
但是使用gets不好,那么更好的方法是什么?
如何刷新stdin?
为什么它不能在以下代码片段中工作?
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <fcntl.h>
int main()
{
int i=0,j=0, sat;
char arg[256];
char * argq;
argq = malloc(sizeof(char)*10);
printf("Input the line\n");
i=read(0, arg, sizeof(char)*9);
arg[i-1]='\0';
fflush(stdin);
i=read(0, argq, sizeof(char)*5);
argq[i-1]='\0';
puts(arg);
puts(argq);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我将输入作为11个字符,则只应读取9个,但是stdin中剩余的两个字符不会被刷新并在argq中再次读取.为什么?
输入:123 456 789
产出:123 456 89
为什么我将这89作为输出?
我正在学习C,我正在使用"getchar()"来停止命令窗口,所以我可以看到练习正在进行,但它只是不起作用.下面是一个样本:
#include <stdio.h>
int main()
{
int value;
printf("1. option 1.\n2. option 2.\n3. option 3.\n4. Exit\n\nMake an option: ");
scanf("%d", &value);
switch (value)
{
case 1:
printf("you selected the option 1.");
break;
case 2:
printf("you selected the option 2.");
break;
case 3:
printf("you selected the option 3.");
break;
case 4:
printf("goodbye");
break;
default:
printf("thats not an option");
break;
}
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
- 选项1.
- 选项2.
- 选项3.
- 出口.
做出选择:1
您选择了选项1.
进程返回0(0x0)执行时间:3.453秒
按任意键继续.
为什么不等待"getchar()"的输入?
我似乎无法理解fflush()C语言中函数的概念。有人可以用更简单的术语来解释它,因为我似乎无法理解它及其在代码中的作用:
int main() {
loadContactList();
while (1) {
printf("\n");
printMenu();
int choice;
scanf(" %d", &choice);
fflush(stdin);
printf("\n");
if (choice == 1) {
// addContact();
} else if (choice == 2) {
} else if (choice == 3) {
} else if (choice == 4) {
query();
} else if (choice == 5) {
while (1) {
printf("choose the sorting mode:\n \n");
printf("1. Sort by last name, first name then number\n");
printf("2. Sort by date\n");
printf("Enter -1 to return …Run Code Online (Sandbox Code Playgroud)