我应该想出一个程序来计算一个作业的单词、元音、小写字母和字母的数量。
我有两个问题,为什么我不能使用while (getchar() != 'n')
而不是将其分配给变量ch
,为什么必须使用fflush(stdin)
???
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch, repeat;
int numVowel = 0, numLower = 0, numAlpha = 0, numWords = 0, inWord = 0;
// Tells user what the program does
printf("This program prompts a user to enter a piece of text andncalculates the number of alphabetic letters, lowercase letters, nvowels and words in that piece of text.nn");
do
{
printf("Type the text here (hit "Enter" to end): ");
while ((ch = getchar()) != 'n') //*dont understand this part*
{
if (ch == ' ')
inWord = 0;
else if (inWord == 0 && isalpha(ch))
{
inWord = 1;
numWords += 1;
}
if (isalpha(ch))
numAlpha += 1;
if (islower(ch))
numLower += 1;
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U': numVowel += 1;
break;
}
}
printf("nNumber of alphabetical letters: %-4dn", numAlpha);
printf("Number of lowercase letters : %-4dn", numLower);
printf("Number of vowels : %-4dn", numVowel);
printf("Number of words : %-4dnn", numWords);
do
{
printf("Do you want to try again? (Y/N): ");
scanf("%c", &repeat);
repeat = toupper(repeat);
if (repeat != 'Y' && repeat != 'N')
printf("Invalid answer. Please enter 'Y' or 'N'.nn");
fflush(stdin); //*why is this required?*
} while (repeat != 'N' && repeat != 'Y');
printf("n");
fflush(stdin); //*why is this required?*
numVowel = 0, numLower = 0, numAlpha = 0, numWords = 0, inWord = 0;
} while (repeat == 'Y');
return 0;
}
为什么我不能使用
while (getchar() != 'n')
而不是将其分配给变量ch
如果这样做,您将无法在while
语句的代码块中使用getchar()
返回的值:if
语句、else if
语句和switch
语句。
为什么必须使用
fflush(stdin)
?
fflush
用于输出流,而不是输入流。因此,fflush(stdin)
是未定义的行为。看见http://en.cppreference.com/w/cpp/io/c/fflush1。
代码中fflush(stdin)
的意图似乎是读取并丢弃所有内容,直到行的末尾。为此编写一个函数。
void readAndDiscardRestOfLine(FILE* in)
{
int c;
while ( (c = fgetc(in)) != EOF && c != 'n');
}
并使用
readAndDiscardRestOfLine(stdin);
而不是
fflush(stdin);
1POSIX为输入流扩展了CCD_ 15的定义。然而,它只将它们扩展到可查找的设备。扩展不适用于stdin
。
使用scanf("%c", &repeat);
扫描字符时会出现问题。通常,用户会输入字符"y"或"n",然后按enter键。字符被读取到repeat
变量中,但输入字符(\n(仍保留在缓冲区中。
当您再次尝试读取字符时,在循环中,您将读取此n
,而不是您所期望的"y"或"n"。
解决方案是将scanf语句更改为
scanf(" %c", &repeat);
%c的fromt中的空格字符将读取任何空白字符,并且只重复存储"y"或"n"。在这种情况下,您将不需要fflush。
fflush(stdin)
不是一个好的做法。有关更多信息,您应该查看Using fflush(stdin(