相关疑难解决方法(0)

如何读取用户在C中输入的字符串?

我想阅读用户使用C程序输入的名称.

为此,我写道:

char name[20];

printf("Enter name: ");
gets(name);
Run Code Online (Sandbox Code Playgroud)

但是使用gets不好,那么更好的方法是什么?

c stdin

47
推荐指数
3
解决办法
18万
查看次数

我无法冲洗stdin

如何刷新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 stdin fflush

17
推荐指数
3
解决办法
5万
查看次数

为什么getchar()不等我在scanf()后按Enter键?

我正在学习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. 选项1.
  2. 选项2.
  3. 选项3.
  4. 出口.

做出选择:1

您选择了选项1.

进程返回0(0x0)执行时间:3.453秒

按任意键继续.

为什么不等待"getchar()"的输入?

c getchar

16
推荐指数
3
解决办法
4万
查看次数

无法理解什么是fflush()函数

我似乎无法理解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)

c

0
推荐指数
1
解决办法
40
查看次数

标签 统计

c ×4

stdin ×2

fflush ×1

getchar ×1