3 回答
TA贡献1776条经验 获得超12个赞
getline() 语法:
istream &getline( char *buffer, streamsize num );
istream &getline( char *buffer, streamsize num, char delim );
用getline()读取字符到buffer中,buffer在代码中通常体现为一个字符数组,streamsize num是一次读入多少个字符, num - 1个字符已经读入, 当碰到一个换行标志, 碰到一个EOF, 或者任意地读入,直到读到字符delim。delim字符不会被放入buffer中。delim字符可以自已设定,默认为回车符'/n'
#include <iostream.h>
#include<stdlib.h>
#include <iomanip.h>
#include <fstream.h>
const int N=10;
int main()
{
char str[N];
ifstream fin;
fin.open("data.txt");
if (!fin)
{
cout<<"error "<<endl;
exit(1);
}
while(fin.getline(str,sizeof(str)))
{
cout<<str;
cout<<endl;
}
cout<<endl;
fin.clear();
cin.get();
return 0;
}
TA贡献1842条经验 获得超12个赞
该法不唯一哦,参考:
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char buf1[50],buf2[50],ch;
int n=0;//?
cout<<"请输入一串字符";
cin.getline(buf1,50);
ofstream outfile("al.txt");
if(!outfile)
{
cout<<"文件打开失败"<<endl;
return 1;
}
outfile<<buf1<<endl;
outfile.close();
ifstream infile("al.txt");
if(!infile)
{
cout<<"文件打开失败"<<endl;
return 1;
}
while(!infile.eof())
{
infile.get(ch);
if(ch>='a'&&ch<='z')
{
ch=ch-'a'+'A';
}
cout<<ch;
buf2[n++]=ch;//?
}
buf2[n] = '\0';
fstream out("a2.txt",ios::out|ios::trunc);
if(!out)
{
cout<<"文件打开失败"<<endl;
return 1;
}
out<<buf2<<endl;//?
out.close();
infile.close();
return 0;
}
添加回答
举报