行和字计数器函数不能正确地相加
Line and word counter function not adding up correctly C++
这个程序应该告诉用户他们的程序中有多少单词和行(仅限文本文件)。我所编写的两个函数都可以正常工作,除了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++)
]
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的for循环不能正确获取argv
- 我是否不正确地集中了这些字符数组?
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- Clang-Format 不能正确分配函数参数
- 可变参数函数模板不能很好地使用 std::function 作为参数
- arm-none-eabi-g++ 不能使用 -flto 正确处理弱别名
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 有没有办法关闭文件? fclose 不能很好地工作
- 为什么相应成员不能正确访问成员函数指针
- 不能很好地运行HElib,但它建立在Windows 10 x64上
- 为什么 ADL 不能使用 std::get 解析为正确的函数
- 不能(隐式地)从字符**转换为常量字符**吗?
- 为什么代码不能返回正确的值?
- 为什么我的节点临时节点不能显示正确的数据?
- STD ::在C 中的进步不能正确地行为
- 为什么我不能使用makefile正确地包含此文件
- 如果更改了,GNU make不能正确地构建头文件
- 行和字计数器函数不能正确地相加
- 在c++中似乎不能正确地向数组中添加对象