山东潍坊一中国际部:C++简单程序

来源:百度文库 编辑:中科新闻网 时间:2024/04/29 04:48:18
Writ a program that, given the name of a file, counts the number of character and lines in that file
写一段程序,输入文件名称,输出这个文件的字数和行数

可能用到的#include<fstream>//ifstream, open(), close(),eof()
#include<string> // string, getline(),find()

老师说用简单的getline()就可以实现

打开并数数的文件只是一个在工作组里的txt文档而已
谢谢
下面的程序好像有一些问题……
麻烦各位再帮帮忙~

最后面的那个已经差不多了,但是运行起来有2个错误
number+=strlen©;/*加上当前行字数*/
有点问题
cout<<"number of character = "<<number<<endl;好像随之有问题

可以帮我解决一下嘛?

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main(void)
{
cout<<"input file name"<<endl;
string filename; /*文件名*/
char c[256]; /*保存每行数据*/
int line=0; /*存储行数*/
double number=0;/*存储字数*/
cin>>filename;
ifstream in(filename.c_str());
if(!in)
{
cout<<"Cannot open OUT file.\n";
return 1;
}

while(!in.eof())
{
in.getline(c,255); /*读取一行*/
number+=strlen(c);/*加上当前行字数*/
line++; /*计算行数*/
}
in.close();

cout<<"Line="<<line<<endl;
cout<<"number of character ="<<number<<endl;
}

晕 我大一的 还没学到系统函数~~~~

#include <fstream.h>
#include <iostream.h>
#include <string>
/*
this program aimed to count the numbers of
character and lines in a file which is existed
in the same directory with this source code
*/
void main()
{
int nCharacterCount = 0;
int nLineCount = 0;
char cTemp[100];
ifstream thefile("count.cpp");//the filename is
//this source file
std::string sLine;

while(!thefile.eof())
{
thefile.getline(cTemp,100);
sLine = cTemp;
nLineCount++;
nCharacterCount = nCharacterCount + sLine.length();
}
cout<<"the Character Count of this file is: "<<nCharacterCount<<endl;
cout<<"the Line Count of this file is: "<<nLineCount<<endl;

}