C++中如何读取文件内容

如题所述

两种读取方法,一种是按行读取,一种是按单词读取,具体如下:

1、按照行读取

string filename = "C:\\Users\\asusa\\Desktop\\蓝桥\\rd.txt";

fstream fin;

fin.open(filename.c_str(), ios::in);

(此处空格一行)

vector<string> v;

string tmp;

(此处空格一行)

while (getline(fin, tmp))

{

v.push_back(tmp);

}

(此处空格一行)

for (auto x : v)

cout << x << endl;

2、按照单词读取

string filename = "C:\\Users\\asusa\\Desktop\\蓝桥\\rd.txt";

fstream fin;

fin.open(filename.c_str(), ios::in);

(此处空格一行)

vector<string> v;

string tmp;

(此处空格一行)

while (fin >> tmp)

{

v.push_back(tmp);

}

(此处空格一行)

for (auto x : v)

cout << x << endl;

扩展资料:

有读取就有写入,下面是写入的方法

//向文件写五次hello。

fstream out;

out.open("C:\\Users\\asusa\\Desktop\\蓝桥\\wr.txt", ios::out);

(此处空格一行)

if (!out.is_open())

{

cout << "读取文件失败" << endl;

}

string s = "hello";

(此处空格一行)

for (int i = 0; i < 5; ++i)

{

out << s.c_str() << endl;

}

out.close();

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-08
/*
*写文件
*/

#include <fstream>
using namespace std;

int main()
{
ofstream ocout;
ocout.open("test.txt");
ocout<<"Hello,C++!";
ocout.close();
return 0;
}

---------------------------------------------------------
/*
*读文件
*
*/

#include <fstream>
#include <iostream>
using namespace std;

int main()
{
ifstream icin;
icin.open("test.txt");
char temp[100];//定义一个字符数组temp
icin>>temp;//将文件中的数据读到字符数组temp中
cout<<temp<<endl;//将temp中存放的内容输出到屏幕上
return 0;
}
第2个回答  推荐于2017-09-23
#include <iostream>//
#include <fstream>
using namespace std;
int main()
{
fstream infile("c:\\data.txt");
string str[6];
int temp[6],i;
for(i=0;i<6;i++)
{
inflie>>str[i]>>temp[i];
}
return 0;
}

用字符串把前面的读取,用整型读取后面的。inflie》是按照空格或者换行区分两个流的。所以一般要知道读取的东西是什么,按照格式来,不然很容易出错。程序我没有调试过,但是应该是能运行的。本回答被提问者采纳
第3个回答  2012-03-15
fopen fgets fclose用这些函数就好了啊。 打开一个文件,获取一行内容,最后关闭。当然还要有一些出错判断以及文件是否结尾的判断,循环取内容。追问

如果文件内容为
black 100
red 200
white 50
black 44
white 33
red 88
如何将数据全部读入

第4个回答  2013-01-09
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
ifstream ifs;
//ifs.open(argv[1]);//传入命令行参数(需要打开的文件文件路径/文件名)
ifs.open("./a.txt",ios::app);

string buf = "\0";
while(getline(ifs,buf))
{
cout << buf << endl;
}
ifs.close();
return 0;
}
相似回答