猿问

我迷惑的是输入带空格的以及读取和写入a2.txt?为什么?

我要把一行带空格的字符串输入到一个文件中
比如 吧 hello world 输入到nu.txt文件中
怎么用getline?
===========================================
下面是附加题(做出来追加分哦~)
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char buf1[50],buf2[50],ch;
cout<<"请输入一串字符";
cin>>buf1;
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;
}
ofstream out("a2.txt");
if(!out)
{
cout<<"文件打开失败"<<endl;
return 1;
}
outfile<<buf2<<endl;
out.close();
infile.close();
return 0;
}
要将一行带空格的字符写入a1.txt中,将其读取并且将所有小写字母改成大写,再写入a2.txt

暮色呼如
浏览 128回答 3
3回答

叮当猫咪

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;}

红颜莎娜

该法不唯一哦,参考:#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;}

芜湖不芜

getline()是从文件读,写的话用fstream
随时随地看视频慕课网APP
我要回答