行和字计数器函数不能正确地相加

Line and word counter function not adding up correctly C++

本文关键字:正确地 不能 函数 字计数 计数器      更新时间:2023-10-16

这个程序应该告诉用户他们的程序中有多少单词和行(仅限文本文件)。我所编写的两个函数都可以正常工作,除了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$ 

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

istream操作符(>>)将检测空格之间的任何一组字符为"word"。所以如果你在解析程序,你可能有:

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

istream操作符将看到4个单词:[for(int, i=1;, i<73;, i++)]