cos*_*mic 1 c++ alphanumeric text-files
我写了一个程序来计算文本文件中的字母数字字符数.但是,它返回的数字总是大于在线字符计数器返回的数字.
例如,程序将计算此文本中的字母数字字符数:
如果这些人有奇怪的时尚和对最特别的事情的期望服从,他们至少准备为他们的怪癖付出代价
再次运行程序,它会说文本中有164个字符.再次运行,它会说有156个字符.使用这个在线字符计数器,似乎字符数应该低于144(在线字符计数器也包括空格).
这是代码:
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main() {
char line[100];
int charcount = 0;
ifstream file("pg1661sample.txt");
while (!file.eof()) {
file.getline(line, 99);
for (int i = 0; i < 100; i++) {
if (isalnum(line[i])) {
charcount++;
}
}
}
cout << endl << "Alphanumeric character count: " << charcount;
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
尝试:
#include <iterator>
#include <algorithm>
#include <iostream>
#include <cctype>
bool isAlphaNum(unsigned char x){return std::isalnum(x);}
int main()
{
std::cout << "Alphanumeric character count: " <<
std::count_if(std::istream_iterator<char>(std::cin),
std::istream_iterator<char>(),
isAlphaNum
) ;
}
Run Code Online (Sandbox Code Playgroud)
代码问题:
在您阅读文件末尾之前,EOF不正确:
// this is true even if there is nothing left to read.
// If fails the first time you read after there is nothing left.
while (!file.eof()) {
// thus this line may fail
file.getline(line, 99);
Run Code Online (Sandbox Code Playgroud)
最好总是这样做:
while(file.getline(line, 99))
Run Code Online (Sandbox Code Playgroud)
只有在getline实际工作时才输入循环.
您还使用了错误版本的getline(因为行可能大于100个字符).
尝试使用与std :: string一起使用的版本,以便它自动扩展.
std::string line;
while(std::getline(file, line))
{
// stuff
}
Run Code Online (Sandbox Code Playgroud)
接下来,假设该行正好是100个字符.
如果这条线只有2个字符长,会发生什么?
for (int i = 0; i < 100; i++)
Run Code Online (Sandbox Code Playgroud)
基本上,您将扫描数据,它将计算从前一行遗留的字母(如果前一行长于当前行)或完全随机的垃圾.如果您仍在使用,file.getline()则可以使用从一行中检索字符数file.gcount().如果使用std :: getline(),那么变量line将是read(line.size())行的确切大小.