c++中如何读取文本文件中的数据

来源:百度知道 编辑:UC知道 时间:2024/06/05 14:18:46
请教各位大侠,我现在需要读txt中的数据,
116 98 133 137 129 120
164 105 168 180 178 141
73 80 184 250 267 188
329 333 288 287 312 173
259 262 290 258 271 232
565 1624 1426 1234 749 123
第一回读
116 98 133 137 129
164 105 168 180 178
73 80 184 250 267
329 333 288 287 312
259 262 290 258 271
565 1624 1426 1234 749
第二回读
98 133 137 129 120
105 168 180 178 141
80 184 250 267 188
333 288 287 312 173
262 290 258 271 232
1624 1426 1234 749 123 不知该如何读取?
大侠,你给的程序我没调通,#include<ifstream>是这个头文件吗?还是#include<fstream>?我的水平 有限,请大侠指点

C++吧。不妨假设读取的文件是“001.txt”
则,我们可以这样做
头文件:
#include<iostream>
#include<ifstream>
#include<string>
using namespace std;

ifstream ifile("1.txt");
if(! ifile) {
cerr<<"error."<<endl;
return -1;
}
string word;
while(ifile>>word) {
cout<<word<<" ";
}

这样就读进去了,不过注意这里读进去没了回车,都用空格分开了,要是要原样的读进去,可以用getline()
ifstream ifile("1.txt");
if(! ifile) {
cerr<<"error."<<endl;
return -1;
}
string lineword;
while(getline(ifile,lineword,'\n')) {
cout<<lineword<<endl;
}

这样就和原来一样了,该换行的换行

利用fread和fwrite格式化读取文件:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{

ifstream in("1.txt");
char c;
while(in.get(c))