c++怎么从文件中读取一个含空格的字符串?

如题所述

给你举个例子吧:

#include <iostream>
#include <fstream>
#include <string>
 
using namespace std;
 
int main()
{
    ofstream wfile;
    ifstream rfile;
    //文件名称
    string filename="123.txt";
    string contents;
    //打开文件
    wfile.open(filename.c_str());
    if(wfile.is_open())
    {
        //写入文件,中间有空格的哈
        wfile<<"Hello, my  name  is  CSDN."<<endl;
    }
    wfile.close();
 
    //从文件中读取内容,包含空格
    rfile.open(filename.c_str());
    if(rfile.is_open())
    {
        //读取一行
        getline(rfile,contents);
    }
    //输出读出的内容,含有空格的哈
    cout<<contents<<endl;
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-08-18
示意:
ifstream in;
in.open("myfile.txt"); // 文件名为myfile.txt
in.getline(str, 80);// str是预先定义的字符数组,最大长度为80
//不过文本文件的一行也要小于80,这句话读到'\n'为止
第2个回答  推荐于2016-06-09
示意:
ifstream in;
in.open("myfile.txt"); // 文件名为myfile.txt
in.getline(str, 80);// str是预先定义的字符数组,最大长度为80
//不过文本文件的一行也要小于80,这句话读到'\n'为止追问

可不可以不用字符数组,用string字符串?

参考资料:http://baike.baidu.com/view/3127321.htm

本回答被提问者采纳
相似回答