gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:13:22 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com