威斯通 并购:继续高分贵求!C++基础问题!在线等
来源:百度文库 编辑:查人人中国名人网 时间:2024/05/10 03:36:01
意思大概是,输入一个文件名,打开该文档(ifstream实现),把最长的那一行输出,然后输出这是第几行,完成
比如打开一个txt文件:
aaaa
aa
aaasdads
aaaaa
输出"aaasdads"
"行数为3”
说的可以详细点吗?多谢!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string file;
cout<<"type the file name:";
cin>>file;
//用ifstream打开文件
ifstream input(file.c_str(),ios::in);
if ( !input.is_open() )
{
//如果没有正常打开则退出
cout<<" invalid file"<<endl;
return;
}
int i = 0;
int nLine = 0; //最长行的行号
int nMaxLength = 0; //最长行的长度
string sOutput ; //最长行的内容
string sContent ;
//一行一行的读取文件里面的内容
while ( getline( input,sContent ) )
{
i ++ ;
if ( (int)sContent.size() > nMaxLength )
{//如果当前行比目前的最长行长,则把当前行作为最长行来处理
nLine = i;
nMaxLength = (int)sContent.size();
sOutput = sContent;
}
}
//读到文件尾,关闭文件,输出最长行信息
input.close();
cout<<"Max Length Line is :" <<nLine<<endl;
cout<<"Content:"<<sOutput<<endl;
system("pause");
}