【发布时间】:2021-07-17 20:33:03
【问题描述】:
我尝试编写一个程序来找出文件中的字符数和单词数:
/*
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
谁能告诉我为什么我没有得到正确的字数?
【问题讨论】:
-
“hello.txt”是否真的包含
Hi Hello Girik Garg? -
是的.. @user306038-----
-
一次读一个字符会很慢。至少一次读取一行并使用
c_str()上的指针或通过索引旋转字符串。您还可以同时计算字符数和断字数。这里不需要两次通行证。 -
你的调试代码有什么有用的吗?
-
对于一个文件的字符数,可以使用文件的大小。寻找到最后,然后读取文件位置。更好的方法是使用操作系统函数来读取文件大小。