c++ - 读取文件中的字符数和单词数
问题描述
我试图编写一个程序来找出文件中的字符数和单词数:
/*
Write C++ program to count:
Number of characters in a file
Number of words in a file
Number of lines in a file
*/
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int countOfCharacters = 0;
int countOfWords = 0;
ifstream ins;
ins.open("hello.txt", ios::in);
char c;
while (ins.get(c))
{
countOfCharacters += 1;
}
cout << "Total Number of characters is " << countOfCharacters << endl;
ins.seekg(0,ios::beg);
while(ins.get(c))
{ cout << "Character is " << c <<endl;
if (c==' ' || c=='.' || c=='\n'){
countOfWords+=1;
}
}
cout << "Total number of words in the file is " <<countOfWords <<endl;
ins.close();
return 0;
}
对于以下输入:
Hi Hello Girik Garg
我得到的输出为:
Total Number of characters is 19
Total number of words in the file is 0
有人能告诉我为什么我没有得到正确的字数吗?
解决方案
当您在第一个读取例程中到达文件末尾时,eofbit
标志设置为true
,为了能够在不关闭/重新打开它的情况下从同一流中读取,您需要重置它:
//...
ins.clear(); //<--
ins.seekg(0, ios::beg);
//...
话虽如此,您可以按照@YSC 的建议在同一个周期中进行这两个计数:
while (ins.get(c))
{
countOfCharacters += 1;
if (c == ' ' || c == '.' || c == '\n')
{
countOfWords += 1;
}
}
请注意,如果该行不以\n
(或'.'
/ ' '
)结尾,则不计算最后一个单词,您应该验证流是否确实打开:
if(ins.is_open(){ /*...*/}
推荐阅读
- django - crontab 似乎启动脚本,但没有任何反应
- flutter - 如何使用 Listview builder 显示 api 响应数据
- python - 从列表末尾删除第n个位置的节点(Leet代码问题19)
- oracle - pl/sql 在 for 循环之前使用 dbms_output.put_line 在文件中添加一次
- python - flow_from_directory 似乎找不到图像但正确识别的类
- javascript - 为什么我的解决信息没有出现在 Promise 中?
- angular - Angular 嵌套的 SVG 组件是不可见的
- sql - 如何更改存储在 Postgres 中的 jsonb 数据的结构
- sql - 如何确定闪电是否两次击中同一个地方?
- javascript - Javascript单元测试错误,存根函数仍在被调用