初学C++,如何读取.txt中的数据到二维数组?(谢谢)

gjshjh 2011-05-15 05:24:46
现在有一个文本文档,里面存了31行,22列数据,怎么样把它读到一个二维数组里面?数据类似下面这样:
96.800000,86.400000,94.285714,100.000000,90.000000,90.000000,
95.733333,86.000000,82.857143,90.000000,80.000000,90.000000,
看了好多贴,但是因为是刚学c++,所以还是看不大懂,但是又很着急的使用,所以恳请哪位能给个可执行的代码,
谢谢了!
...全文
152 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
gjshjh 2011-05-15
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 my_id_is_null 的回复:]
C/C++ code

谢谢啦
gjshjh 2011-05-15
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 songyzhang 的回复:]
简单的写了下:


谢谢,学习一下
winginsky 2011-05-15
  • 打赏
  • 举报
回复

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

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

string strFileName;
cin>>strFileName;
ifstream file(strFileName.c_str(),ios::in);
if(!file)
return 0;
string line;
vector<vector<string>*>* array=new vector<vector<string>*>;
while(getline(file,line,'\n'))
{
vector<string>* vecTmp=new vector<string>;
int pos=0;
int prev_pos=0;
while((pos=line.find_first_of(',',pos))!=string::npos)
{
vecTmp->push_back(line.substr(prev_pos,pos));
cout<<line.substr(prev_pos,pos)<<endl;
prev_pos=++pos;
}
array->push_back(vecTmp);

}
printf("Hello World!\n");
return 0;
}

songyzhang 2011-05-15
  • 打赏
  • 举报
回复
简单的写了下:


#include<stdio.h>
#include<stdlib.h>
#define LARGEST_ROW 3
#define LARGEST_COL 4
int main()
{
float data[LARGEST_ROW][LARGEST_COL];
FILE* fp;
float temp;
char value[20];
int i , j ,k ;
int c;
i = j = k = 0;
if((fp = fopen("/home/syz/example/data.txt","r")) == NULL)
{
printf("Open the file fail!\n");
return -1;
}

while((c = fgetc(fp)) != EOF)
{
switch(c)
{
case '\n':
value[k] = '\0';
temp = atof(value);
data[i][j] = temp;
k = 0;
i++;
j = 0;
break;
case ' ': //为了去掉逗号前后可能的空格
break;
case ',':
value[k] = '\0';
temp = atof(value);
data[i][j] = temp;
k = 0;
j++;
break;
default:
value[k] = (char)c;
k++;
}
}
for( i = 0; i < LARGEST_ROW; i++)
{
for( j = 0; j <LARGEST_COL; j++)
{
printf("%.4f\t", data[i][j]);
}
printf("\n");
}

fclose(fp);
return 0;

}
yjueqtd 2011-05-15
  • 打赏
  • 举报
回复
查找逗号和换行符啊。
bdmh 2011-05-15
  • 打赏
  • 举报
回复
逐行逐个的处理

64,662

社区成员

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

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