行和单词计数器功能无法正确添加C ++

时间:2015-07-30 19:02:22

标签: c++ function counter

该程序应该告诉用户他们的程序中有多少单词和行(仅限文本文件)。除了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$ 

1 个答案:

答案 0 :(得分:0)

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

istream运算符(&gt;&gt;)将检测空格之间的任何字符组是否为“单词”。因此,如果您正在解析程序,您可能会:

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

istream运算符会看到4个字:[for(inti=1;i<73;i++)]