最近在搬运John Burkardt的c++代码时,发现了很多问题,下面的代码使用来获取文本文件的行数的(其中,空行,以及以#开头的行不计入行数),代码如下:
# include <iostream>
# include <fstream>
# include <string>
using namespace std;
int file_row_count ( string input_filename );
int s_len_trim ( string s );
int main()
{
string c = "";
cout << c.length() << endl;
cout << s_len_trim(c) << endl;
string filename = "";
cin >> filename;
int r = file_row_count(filename);
cout << r << endl;
return 0;
}
int file_row_count ( string input_filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_ROW_COUNT counts the number of row records in a file.
//
// Discussion:
//
// It does not count lines that are blank, or that begin with a
// comment symbol '#'.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 June 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int FILE_ROW_COUNT, the number of rows found.
//
{
int bad_num;
int comment_num;
ifstream input;
//int i;
char line[255];
//string line;
int record_num;
int row_num;
row_num = 0;
comment_num = 0;
record_num = 0;
bad_num = 0;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "FILE_ROW_COUNT - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
for ( ; ; )
{
input.getline ( line, sizeof ( line ) );
//getline(input,line);
if ( input.eof())
{
break;
}
record_num = record_num + 1;
if ( line[0] == '#' )
{
comment_num = comment_num + 1;
continue;
}
if ( s_len_trim ( line ) == 0 )
{
comment_num = comment_num + 1;
continue;
}
row_num = row_num + 1;
}
input.close ( );
return row_num;
}
int s_len_trim ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_LEN_TRIM returns the length of a string to the last nonblank.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string.
//
// Output, int S_LEN_TRIM, the length of the string to the last nonblank.
// If S_LEN_TRIM is 0, then the string is entirely blank.
//
{
int n;
n = s.length ( );
while ( 0 < n )
{
if ( s[n-1] != ' ' && s[n-1] != '\n' && s[n-1] != '\t' )
{
return n;
}
n = n - 1;
}
return n;
}
测试文件内容为:
# ell.txt
#
# Spatial dimension M = 2
# Number of points N = 21
#
0.0 0.0
1.0 0.0
2.0 0.0
3.0 0.0
4.0 0.0
0.0 1.0
1.0 1.0
2.0 1.0
3.0 1.0
4.0 1.0
0.0 2.0
1.0 2.0
2.0 2.0
3.0 2.0
4.0 2.0
0.0 3.0
1.0 3.0
2.0 3.0
0.0 4.0
1.0 4.0
2.0 4.0
此文件末尾没有空行,完整的数据应该是21行,但执行结果却显示20行
然后,我在此文件的末尾添加了一个空行,执行结果显示是21行,初步猜想应该是判断文件结束标志EOF时出现了问题,先记录下,麻烦各位大神看到此文时,也试试,给我提点建议,谢谢!!!