岗位粉尘监测标准:求助各位C++的Professor,编写一个简练的C++程序(急需)

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/07 07:12:49
Write a program to ask user to enter a filename for reading . Read the lines in the file and display the longest line on the screen with corresponding line number.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main( ) {

    cout << "Please enter the name of the file to be read: ";
    string fname;
    cin >> fname;

    ifstream in( fname.c_str( ) );
    if( ! in ) {
        cout << "Error: File not found or can't be read.\n";
        return 1;
    }

    string s;
    getline( in, s );
    string longest = s;
    int lineNum = 1;

    int line = 2;
    while( getline( in, s ) ) {
        if( longest.size( ) < s.size( ) ) {
            longest = s;
            lineNum = line;
        }
        ++line;
    }

    cout << "The longest line is line number " << lineNum << ":\n"
         << longest << endl;

    return 0;
}