【问题标题】:Line and word counter function not adding up correctly C++行和字计数器功能未正确加起来 C++
【发布时间】:2026-02-16 18:15:01
【问题描述】:

这个程序应该告诉用户他们的程序中有多少单词和多少行(仅限文本文件)。我编写的两个函数都可以工作,除了 num_of_lines 函数每次计算的行数都比正确的多一行,而 num_of_words 函数每次都会减少大约 300 个单词。不知道我在这里做错了什么。任何帮助将不胜感激,谢谢。我在我的代码之后复制并粘贴了一个输出,并将其与 wc 进行了比较。

#include <iostream>
#include <fstream>
#include <cctype>
#define die(errmsg) {cerr << errmsg << endl; exit(1);} 
using namespace std;

int num_of_words(string name)
{
    int cnt2 = 0;

    ifstream iwords;
    iwords.open(name);

    string w;
    if(iwords.is_open())
    {
        while(iwords >> w)
        {
            cnt2++;
        }
    }   
    else cerr <<"can not open" + name << endl;      
    iwords.close();
    return(cnt2);
}

int num_of_lines(string name)
{
    int cnt3 = 0;
    string line;

    ifstream ilines;     

    ilines.open(name);        

    if(ilines.is_open())
    {
        while(getline(ilines, line))
        {
            cnt3++;
        }   
    }  
    else cerr <<"can not open" + name << endl;
    ilines.close(); 
    return(cnt3);
}



int main(int argc, char **argv)
{ 
    int num_of_lines(string name);

    if(argc == 1)die("usage: mywc your_file"); 

    string file;
    file = argv[1];

    ifstream ifs;

    ifs.open(file);

    if(ifs.is_open())
    {
        int b;

        b = num_of_words(file);

        cout <<"Words: " << b << endl;
    }
    else
    {
        cerr <<"Could not open: " << file << endl;
        exit(1);
    }
    ifs.close();

    return(0);
}

Zacharys-MBP:c++ Zstow$ my sample.txt 
Chars: 59526
Words: 1689
Lines: 762
Zacharys-MBP:c++ Zstow$ wc sample.txt
     761    2720   59526 sample.txt
Zacharys-MBP:c++ Zstow$ 

【问题讨论】:

  • 文件长什么样?单行文件是 300 吗?
  • 最好不要将代码与 C++ 中的 while 循环放在同一行。
  • 我们能否举一个例子,说明一行“单词”以及您的程序计算得出的“单词”数量?
  • 只针对文本文件,单行文件的结果是一样的。
  • 我复制并粘贴了输出,并将其与 wc 进行了比较,因此您可以看到它偏离了多少。我猜字数差了 700-800。

标签: c++ function counter


【解决方案1】:

大多数文件(尤其是程序)将以新行结尾。您可能在编辑器中看不到它,但它可能存在。您必须检查最后一行以查看它是否实际包含任何内容,或者它是否为空。

istream 运算符 (>>) 将检测空格之间的任何字符组作为“单词”。所以如果你在解析程序,你可能有:

for(int i=1; i<73; i++)

istream 运算符将看到 4 个字:[for(int, i=1;, i&lt;73;, i++)]

【讨论】:

  • 我猜getline() 会返回一个空字符串,如果该行是空的。只是一个想法,你可能想检查一下。 :-)
  • if(getline(ilines, line) == " ")cnt3--;我试过这个,但编译错误,不知道如何格式化。
  • if(!getline(ilines, line))cnt3--;还有这个,但它把线条切成了两半。