注册 登录
编程论坛 C++教室

C++中怎样从文件中读取字符到一个字符数组中

chaoqun9527 发布于 2011-05-14 12:25, 5617 次点击
今天将C程序改为C++程序,想从文件中读取字符到字符数组中再进行遍历操作,输出到屏幕上,不知道怎么弄,先打开文件,然后不知怎么读取其内容到字符数组中,请教高人!
3 回复
#2
寒风中的细雨2011-05-14 21:51
程序代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const string GetFileName(void);
void ReadFile(const string strFileName);

int main(void)
{
    ReadFile(GetFileName());
    cout << endl;

    return 0;
}

const string GetFileName(void)
{
    string strFileName;
    cout.setf(ios::right);
    cout.width(30);
    cout << "输入文件的路径:";
    cin >> strFileName;

    return strFileName;
}

void ReadFile(const string strFileName)
{
    string text;

    ifstream in(strFileName.c_str());

    if (!in)
    {
        cout.width(15);
        cout << "文件打开失败" << endl;
    }

    while (in >> text)
    {
        cout << text;
    }

    in.close();
    in.clear();
}
#3
寒风中的细雨2011-05-14 21:53
只有本站会员才能查看附件,请 登录
读取的是上面代码文件
#4
chaoqun95272011-05-15 22:56
谢谢,回去试试吧,呵呵
1