C语言编写3. 从键盘输入一段字符,存入文件中...

从键盘输入一段字符,存入文件中,统计字符个数,对这段字符进行查找子串和删除子串的操作,结果存入另一个文件中。

第1个回答  2009-09-29
以下当参考吧,c++写的--文本文件的输入输出,以及统计英文文本的行数字符数,单词数。改一下头文件,cout cin 改printf scanf 就是了。
方法还是可以借鉴的~

输入:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
main()
{
string line;//不可以用char定义。
string filename;
fstream file;
cout<<"please input the filename:";
cin>>filename;
file.open(filename.c_str());//输入的是D:\guo.txt
if(!file)
{
cout<<"file open fail"<<endl;
}
while(getline(file, line, '\r'))//从文件中读取字符串到输入输出流中。不可以换成get()。
{
cout<<line<<endl;
}
file.close();
return 0;
}

或者:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
main()
{
static int line;
static int num;
char ch;
string stringline;
string filename;
ifstream file;
cout<<"please input the filename:";
cin>>filename;
file.open(filename.c_str());//输入的是D:\guo.txt

if(!file)
{
cerr<<"file open fail"<<endl;
exit(-1);
}
else
{
cout<<"the artical is:"<<endl;
while(file.get(ch))
{
cout.put(ch);
}
file.close();
}
return 0;
}

输出:

#include<iostream>
#include<fstream>
using namespace std;
main()
{
char *line=new char;
fstream file;
file.open("d:\\guo.txt",ios::out|ios::trunc);
if(!file)
{
cerr<<"file open or creat error"<<endl;
exit(1);
}
while(cin.get(line,100))
{
file<<line<<endl;
if(cin.get()==' ')
break;
}
file.close();
}

或者:

#include<iostream>
#include<fstream>
using namespace std;
main()
{
char *line=new char;
fstream file;
file.open("d:\\guo.txt",ios::out|ios::trunc);
if(!file)
{
cerr<<"file open or creat error"<<endl;
exit(1);
}
do
{
cin.getline(line,100);
file<<line<<endl;
}
while(strlen(line)>0&&!cin.eof());
file.close();
}
C++ 统计英文文本 中的 行数 单词数
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
main()
{
int num0=0;
int num1=0;
int tempernum0=0;
int line=0;
int i;
string str;//不可以用char定义。
string filename;
fstream file;
cout<<"please input the filename:";
cin>>filename;
file.open(filename.c_str());//输入的是D:\guo.txt
if(!file)
{
cout<<"file open fail"<<endl;
}
cout<<"文本中的内容是:"<<endl;
while(getline(file, str, '\n'))
{
cout<<str<<endl;//文本输出
line++;//行数统计
int n=str.length();
if(n!=0)
tempernum0++;//统计非空行末尾的单词数目
string::iterator itr=str.begin();
for(i=0;i<n-1;i++)
{
if(itr[i]==' '&&itr[i+1]!=' ')
num0++;//字数统计,非空行末尾的单词没有被统计进去,最后要再加上非空行的行数。
}
for(i=0;i<n;i++)
{
if(itr[i]!=' ')
num1++;//字符数目统计
}
}
cout<<"行数是:"<<line<<endl;
cout<<"单词数是:"<<num0+tempernum0<<endl;
cout<<"字符数是:"<<num1<<endl;
file.close();
return 0;
}本回答被提问者采纳
相似回答