3 回答

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
getline() 語(yǔ)法:
istream &getline( char *buffer, streamsize num );
istream &getline( char *buffer, streamsize num, char delim );
用getline()讀取字符到buffer中,buffer在代碼中通常體現(xiàn)為一個(gè)字符數(shù)組,streamsize num是一次讀入多少個(gè)字符, num - 1個(gè)字符已經(jīng)讀入, 當(dāng)碰到一個(gè)換行標(biāo)志, 碰到一個(gè)EOF, 或者任意地讀入,直到讀到字符delim。delim字符不會(huì)被放入buffer中。delim字符可以自已設(shè)定,默認(rèn)為回車符'/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貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
該法不唯一哦,參考:
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char buf1[50],buf2[50],ch;
int n=0;//?
cout<<"請(qǐng)輸入一串字符";
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;
}
添加回答
舉報(bào)