c - scanf 已跳过(尝试添加空格并\n)

标签 c

我正在尝试对文本文档进行文件重定向,并让我的代码读取它并输出代码中存在的字符数,并允许用户输入不区分大小写的字母,指示程序查看文本并返回该字母出现的次数。

scanf 无法正常工作并且无法获取用户输入。

我尝试添加这样的空格:“%c”和“%c\n”。 尝试删除 & 并使用 getchar();

#include <stdio.h>

// Defining variables

#define SIZE 8000

int main(void)
{
        char case1 = 'a', case2 = 'b', data[SIZE];

        int i, count;

// Reading in the .txt file into a 8000 sized array and removing any other unnecessary portions from the array.
    for (i = 0; i < 8000; i++)
    {
        fscanf(stdin, "%c", &data[i]);
    }

        printf("The text from the file: \n\n");

    for (i = 0; data[i] != '\0'; i++)
    {
        printf("%c", data[i]);
    }

// Printing out the .txt document and counts the number of characters
        printf("\n");
        printf("There are a total of %i characters in that text.\n ", i+1);
        printf("Enter a character to search for in the text:\n ");

// Exiting from stdin.

        if (!freopen("/dev/tty", "r", stdin))
    {
        perror("/dev/tty");
        exit(1);
    }

// Asking for user input.

        scanf("%c", &case1);

// Converting user input into different lettercase.


    if (case1 == toupper(case1))
    {
        case1 = tolower(case1);
    } else
    {
        case2 = toupper(case2);
    }
        printf("This is your input: %c. Also searching for:  %c.\n", case1,case2);

// Searching the text for user-inputted letter.

    for (i = 0; data[i] != '\0'; i++)
    {
        if (data[i] == case1)
        {
        count++;
        }
        else if (data[i] == case2)
        {
        count++;
        }

    }

        printf("That letter %c appears a total of %i times.\n", case1, count);
        return 0;
}

最佳答案

您正在 stdin 上使用 fscanf(),这相当于 scanf()。如果您的 8000 个字符输入不以换行符结尾,fscanf() 直到出现换行符才会返回,并且 8000 个字符之后输入的任何内容都将被 case1 接受code> 在最后的 scanf() 调用中。

这就是 scanf() 调用不是“跳过”的,而是读取缓冲区中已有的字符。如果该字符不是空格,您尝试的“修复”将是不够的。

for (i = 0; i < SIZE; i++)
{
    fscanf(stdin, "%c", &data[i]);
}

// Flush all remaining input up-to next newline
int c ;
do {} while( data[SIZE-1] != `\n` && 
             (c = getchar()) != `\n` && 
             c != EOF ) ;

关于c - scanf 已跳过(尝试添加空格并\n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053800/

相关文章:

c - 如何访问C中分配的内存?

c - C 中的冒泡排序显示段错误

我可以设置工作队列的优先级吗?

C99 通过带大括号的指针初始化数组

java - 如何将c代码移植到java中?启动说明

c - STM32闪烁的LED错误寄存器?

分配给较大宽度的整数时的 C 整数溢出行为

c - fork() 和 wait() 有两个子进程

我可以假设 OpenMP 共享变量是原子读写的吗?

c - 为什么 &p+1 给出与 p 相同的结果