读书人

初学者请问从文本文件中读取数据

发布时间: 2012-03-07 09:13:51 作者: rapoo

菜鸟请教从文本文件中读取数据
data1.txt

1.0341 2.0641 3.0671 4.0861 5.2435 ...
6.7544 7.2424 8.3353 9.3511 10.1134 ...

---------------------------

要读取data1.txt中数据到两个数组x(n),y(n)中(如n=5),使第一行为x的值,第二行为y的值,如下:
x[1]=1.0341 x[2]=2.0641 x[3]=3.0671 x[4]=4.0861 x[5]=5.2435 ...
y[1]=6.7544 y[2]=7.2424 y[3]=8.3353 y[4]=9.3511 y[5]=10.1134 ...

请帮忙补充一下省略号中的代码或者按你自己习惯写法.
还有这个data1.txt文件正确放在哪里?我放在同read.cpp主文件同一个project目录下,编译时说找不到这个文本文件,路径发生错误. 我是刚接触c++,请大家指教,谢谢!


read.cpp

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

int main () {
float x(5),y(5);
string line;
ifstream myfile ( "data1.txt ");
if (myfile.is_open())
{
.....


myfile.close();
}
else cout < < "Unable to open file ";

cout < < x[1] < < endl;
return 0;
}

[解决办法]
#include <cstdlib>
#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
float x[5],y[5];
ifstream myfile ( "data.txt ");

int i;
if(!myfile.fail())
{
for(i=0; i <5; i++) myfile> > x[i];
for(i=0; i <5; i++) myfile> > y[i];

for(i=0; i <5; i++) cout < <x[i] < < "\t ";
cout < <endl;
for(i=0; i <5; i++) cout < <y[i] < < "\t ";
cout < <endl;
}
else cout < < "Unable to open file ";

system( "PAUSE ");
return 0;
}

[解决办法]

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

int main () {
float x[2][5];
string line;
ifstream myfile;
myfile.open( "d:\\data1.txt ", fstream::in);

int i=0, j=0;
if (myfile.is_open())
{
string line;

while(getline(myfile, line))
{
string word;
istringstream stream(line);
while(stream> > word)
{
char * temp = (char *)word.c_str();;
x[j][i] = (float)atof(temp);
i++;
}
j++;
}
myfile.close();
}
else cout < < "Unable to open file ";


for(j=0; j <2; j++)
{
for(i=0; i <5; i++)
{
cout < <x[j][i] < < " ";
}
cout < <endl;
}


system( "PAUSE ");
return EXIT_SUCCESS;
}


---------------------
还有点小问题.
------解决方案--------------------


ifstream myfile ( "data1.txt ")中 "data1.txt "是相对路径,不该的调试状态话放在工程文件夹的debug文件夹里,release版的话和exe文件放一个文件夹就行了。
如果是想放到其他文件夹有两个办法,一个是用绝对路径,另外一个是运行时读取路径到变量中,具体方法就要看情况了。
[解决办法]

myfile.open( "d:\\data1.txt ", fstream::in);
将上面那个改为myfile.open( "data1.txt ", fstream::in);就可以了,
不过第二行的输出就好象不行啦
还有这个data1.txt文件放在同read.cpp主文件同一个project目录下

读书人网 >C++

热点推荐