用C++计算输入文本的新行数

Counting new lines of the input text in C++

本文关键字:新行数 文本 输入 C++ 计算      更新时间:2023-10-16

我是编程新手,我必须编写一个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: %dn", characters);
printf("Number of Words: %dn", words);
printf("Number of Lines: %dn", newlines);
}
return 0;
}
  • 您的尝试做出了一个重要的假设:单词由一个空格分隔。在现实世界中,单词可以由一个以上的空格或甚至其他字符(如TAB;(分隔。假设输入提供用一个空格分隔的单词,仍然不能忽略一行中以NLEOF结尾的最后一个单词
  • 您的计数器必须初始化为零
  • 不要使用getchar来获取字符使用C++的控制台输入cinchar变量。默认情况下,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;
  • 了解如何使用调试器
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;
}
}

这个怎么样:

int count_lines(const std::string& s)
{
return std::accumulate(s.cbegin(), s.cend(), 0, [](int prev, char c) { return c != 'n' ? prev : prev + 1; });
}