【发布时间】: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。