我是编程新手,我必须编写一个C程序,要求从键盘输入文本。该程序的输出应为字符数,单词数和已键入的行数。多个连续空格不应视为多个单词。 我的程序正确地计算了字符和单词的数量,但是新行的输出为0。我不知道为什么它不进行迭代。我是一个新手,所以对不起,如果我说错了一个问题,或者没有提供足够的信息并且看不到真正明显的东西,对不起。谢谢。
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int a;
int characters = -1;
int words = 1;
int newlines = 0;
cout << "Please enter your string: ";
while ((a = getchar()) != EOF)
{
if (a != ' ')
{
characters++;
}
else if (a == ' ')
{
words++;
}
else if (a == '\n')
{
newlines++;
}
printf("Number of Characters: %d\n", characters);
printf("Number of Words: %d\n", words);
printf("Number of Lines: %d\n", newlines);
}
return 0;
}
答案 0 :(得分:2)
TAB
或;
)。假设输入提供的单词之间用一个空格隔开,那么您仍然不能忽略行中的最后一个单词以NL
或EOF
结尾。getchar
来获取字符。 使用C ++的控制台输入cin
和一个char
变量。默认情况下,cin
会忽略空格,但是您需要它们:使用noskipws
操纵符来考虑空格:
#include "stdafx.h"
#include <iostream>
//...
char a;
while ( cin >> noskipws >> a )
{
// ...
switch
代替if
:
while ( cin >> noskipws >> a )
{
switch ( a )
{
default:
characters++;
continue;
case ' ':
words++;
continue; // continues with while
case '\n':
newlines++;
words++;
continue;
case '\x1a': // ctrl + z
break;
}
break;
}
words++;
newlines++;
while
循环的外部上打印。使用 C ++的控制台输出cout
代替printf
:
cout
<< "Number of Characters: " << characters << endl
<< "Number of Words: " << words << endl
<< "Number of Lines: " << newlines;
答案 1 :(得分:1)
if (a != ' ') // << this applies for `\n` AS WELL!!!
{
characters++;
}
else if (a == ' ') // << obsolete! if a is not unequal to ' ', it IS ' '
{
words++;
}
else if (a == '\n') // won't ever be reached!
{
newlines++;
}
首先检查特殊字符:
if (a == ' ')
{
words++;
}
else if (a == '\n')
{
newlines++;
}
else // ANYTHING else...
{
characters++;
}
但是,如果后面有空格,您的实现将无法正确计数单词!您需要记住,如果最后一个字符是字母数字字符或任何空格或换行符,并且仅在前一个字符是字母数字字符时才对单词计数。如果您也不想单独计算空行,则必须以类似方式处理。
您可能会考虑:
unsigned int characters = 0; // count characters just as appear
unsigned int words = 0; // no words on empty lines!
unsigned int newlines = 0; // alternatively: number of lines, then start with 1
// (line without newline still is a line...)
bool isSpace = true; // first input character alphanumeric -> word counted...
while(a = ...)
{
switch(a)
{
case '\n':
++newlines;
// no break!
case ' ':
isSpace = true;
break;
default:
++characters;
if(isSpace)
{
++words;
isSpace = false;
}
break;
}
}