【问题标题】:Having user input in C在 C 中进行用户输入
【发布时间】:2021-06-08 00:47:03
【问题描述】:

我的 C 代码有问题。请看下面的代码:

#include<stdio.h>

int main()
{
    char name[30]; // Declaring the string-array
    FILE* fileptr; // Declaring the FILE pointer
    char file[10];
    printf("Please enter the file name : ");
    scanf("%s",file);//Taking a single word input
    fileptr = fopen(file,"w");
    if (fileptr == NULL)
    {
        printf("No such file found !");

    }
    puts("Please enter some strings here: ");
    gets(name);  //Line 17
    fputs(name,fileptr);
    printf("\nStrings saved to %s",file);
    fclose(fileptr);

}

问题出在第 17 行,我使用 gets() 而不是 scanf() 但我不知道它是否正确。我无法在此处使用 gets() 或其他功能获得任何用户输入。但是我想输入多个单词或行字符串,并在打印第 16 行后跳过,然后打印第 19 行。它没有给我任何输入的机会。我该怎么办? 请帮帮我。 提前致谢。 :)

【问题讨论】:

  • “我无法获得任何用户输入”。你能澄清一下这到底是什么意思吗?给出准确的输入、预期行为和实际行为。
  • 我应该使用什么来获取多行用户输入?
  • 永远不要使用gets()——它不安全。添加一个循环以获取多行输入。请注意,gets() 会删除换行符,fputs)) 不会添加它们。
  • 请注意,scanf() 在输入中留下了一个换行符,gets() 立即读取并丢弃并返回一个空字符串。

标签: c function


【解决方案1】:

像这样添加一个名为remove_trash的函数

void remove_trash(void)
{
    char trash[81];
    fgets(trash, 80, stdin);
}

在做之前调用它gets(name) //Line 17.

【讨论】:

    【解决方案2】:

    您可以使用scanf 来读取格式化的输入,但需要小心使用,以免导致缓冲区溢出。要安全读取字符串,您需要使用fgets,从定义阈值的stdin 读取。

    如手册中所述:

    char *fgets(char *restrict s, int size, FILE *restrict stream);
    
    // fgets() reads in at most one less than size characters from stream
    // and stores them into the buffer pointed to by s. Reading stops after
    // an EOF or a newline. If a newline is read, it is stored into the buffer.
    // A terminating null byte ('\0') is stored after the last character in the
    // buffer. 
    

    【讨论】:

    • 我使用了fgets(),但它也不起作用。我使用了scanf(),但希望对字符串输入进行更多控制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多