大家好,我想计算项目的单词和字符等的数量。但是,在我输入^ D终止输入的行中,该行不计入字符等中。
输入终止的任何行均不计数。此外,由于某种原因,当我运行该程序时,它不会在底部显示语句,但在调试时会显示。
非常感谢您的帮助。
#include <stdio.h>
int main()
{
int input;
int words =0;
int charecters =0;
int spaces =0;
int newline =0;
int tab= 0;
int total =0;
int dummy;
int lastChar;
printf("Please start your input and press ^D to terminate:\n");
while ((input=getchar())!= EOF)
{
if(input == ' ')
{
++spaces;
}
else if(input =='\n')
{
++newline;
fflush(stdin);
}
else if(input == '\t' )
{
++tab;
}
else
{
charecters++;
dummy = input;
}
lastChar = input;
if(dummy != lastChar)
{
words++;
}
total++;
}
printf("The total number of keyboard strokes was %d.\n", total);
printf("The total number of charecters is %d\n", charecters);
printf("The number of new lines is: %d\n", newline);
printf("The number of space is: %d\n", spaces);
printf("The number of tabs is: %d\n", tab);
printf("The number of new words is: %d\n", words);
return 0;
}
最佳答案
以下建议的代码:
<ctrl-d>
识别为输入的末尾,它必须是新行switch
语句,以使每个“ Activity ”清晰可见characters
的拼写现在,建议的代码为:
#include <stdio.h>
int main( void )
{
int input;
int words = 0;
int charecters = 0;
int spaces = 0;
int newline = 0;
int tab = 0;
int total = 0;
printf( "Please start your input and press ^D to terminate:\n" );
enum { inWord, notInWord } state = notInWord;
while ( (input=getchar())!= EOF )
{
++total;
if( input == ' ' || input == '\n' || input == '\t' )
{
state = notInWord;
}
switch( input )
{
case ' ':
++spaces;
break;
case '\n':
++newline;
break;
case '\t':
++tab;
break;
default:
charecters++;
if (state == notInWord )
{
state = inWord;
++words;
}
}
}
printf( "The total number of keyboard strokes was %d.\n", total );
printf( "The total number of charecters is %d\n", charecters );
printf( "The number of new lines is: %d\n", newline );
printf( "The number of space is: %d\n", spaces );
printf( "The number of tabs is: %d\n", tab );
printf( "The number of new words is: %d\n", words );
return 0;
}
该程序的典型运行:
Please start your input and press ^D to terminate:
lkfjaiennf;aliea vliesge lsker'
flkaiwore
The total number of keyboard strokes was 42.
The total number of charecters is 38
The number of new lines is: 2
The number of space is: 2
The number of tabs is: 0
The number of new words is: 4
请注意,程序无法将标点符号识别为单词分隔符。建议包括头文件
ctype.h
,以使用以下功能使代码更健壮:ispunc()
isdigit()
isspace()
关于c++ - 循环终止时无法获得输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61560855/