c++读取数据文件

Wadejr 2009-08-14 11:40:13
比如有数据文件如下:

1 1.0 2.0 3.0
2 2.0 3.0
3 1.0
4 2.0 2.0
5 4.0 3.0 2.0

数据每行共4项,分别要赋值给四个数组 每行数据格式是固定的 空缺的用0补

请教如何能够正确读取每行的数据并赋值?
...全文
249 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Wadejr 2009-08-28
  • 打赏
  • 举报
回复
已经解决,谢谢各位
zfufan 2009-08-16
  • 打赏
  • 举报
回复
mark
mstlq 2009-08-15
  • 打赏
  • 举报
回复
随手写一个……

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


int main()
{
int a1[256];
float a2[256],a3[256],a4[256];
ifstream ifs("g:\\ll.txt");
if(!ifs) {
printf("can not open file!\n");
return 1;}
stringstream tmp;
string str;
char buffer[256];
int i=0;
while(ifs.getline(buffer,255) && i<256)
{
tmp.clear();
tmp<<buffer;
tmp>>a1[i];
if (tmp.bad()) {a1[i]=0;a2[i]=a3[i]=a4[i]=0;}
tmp>>a2[i];
if (tmp.bad()) {a2[i]=a3[i]=a4[i]=0;}
tmp>>a3[i];
if (tmp.bad()) {a3[i]=a4[i]=0;}
tmp>>a4[i];
if (tmp.bad()) {a4[i]=0;}
i++;
};
for(int ii=0;ii<i;++ii)
printf("line%d:\n%d %.1f %.1f %.1f \n",ii+1,a1[ii],a2[ii],a3[ii],a4[ii]);
return 0;
}
ljx87085210 2009-08-15
  • 打赏
  • 举报
回复
顶一下
zzandyc 2009-08-15
  • 打赏
  • 举报
回复
支持楼上的,接分
lsm164 2009-08-15
  • 打赏
  • 举报
回复
来个面向对象的:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstring>
using namespace std;

class myData
{
public:
myData()
: m_index(0),
m_d1(0),
m_d2(0),
m_d3(0)
{
}

void set(const char* buf)
{
stringstream stream(buf);
stream >> m_index;
stream >> m_d1;
stream >> m_d2;
stream >> m_d3;
}

void print() const
{
std::cout << m_index << " ";
std::cout << m_d1 << " ";
std::cout << m_d2 << " ";
std::cout << m_d3 << std::endl;
}
private:
int m_index;
double m_d1;
double m_d2;
double m_d3;
};

int
main(int argc, const char* argv[])
{

ifstream stream("test.txt");
vector<myData> vec_data;
char buf[256];
while (stream.getline(buf, 256))
{
if (0 == strlen(buf))
{
//过滤空行
continue;
}
myData tmp_data;
tmp_data.set(buf);
vec_data.push_back(tmp_data);
}

vector<myData>::iterator iter;
for (iter = vec_data.begin(); iter != vec_data.end(); iter++)
{
iter->print();
}

}
lwlchristy 2009-08-15
  • 打赏
  • 举报
回复
3楼的顶一个!
superbtl 2009-08-15
  • 打赏
  • 举报
回复
UP
alan001 2009-08-15
  • 打赏
  • 举报
回复
up
fblgzdq 2009-08-15
  • 打赏
  • 举报
回复
回一个
接分
adventurelw 2009-08-14
  • 打赏
  • 举报
回复
ifstream fin;
用fin.getline读取数据
然后用istringstream os格式化成字符串流

double d;
os >> d可以读取已有的浮点数据
如果读完了不够四个数,补零就可以。
hua_zhixing_ 2009-08-14
  • 打赏
  • 举报
回复
用c++很简单的,看书吧。

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧