假设一个文件存储数据如下图,现在要把这里面的每个数据都读取出来存到数组里,
10 10
0 0 0 1 0 0 0 0 0 1
0 0 1 1 1 0 1 1 0 1
0 0 0 0 1 0 1 0 0 1
1 0 0 1 0 0 1 1 0 1
0 1 0 1 1 0 1 0 1 1
0 1 0 0 0 1 0 1 0 0
1 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 1
0 0 0 1 0 0 1 1 0 0
1 0 0 0 0 0 0 0 0 0
在读取下面的0101...时我的做法是按行读取
ifstream file("...");
while(getline(file,content))
{
content.erase(remove(content.begin(), content.end(),' '),content.end());
++i;
strcpy(a,content.c_str());
}
但是当读取第一行的时候(10 10) :
读这种并不大的文件,比较好的习惯是先统一读到内存中,再做解析。由于这个文件格式并不复杂,解析其实非常简单。
#include <iostream>
#include <fstream>
#include <sstream>
int main()
{
const int size = 10*10+2;
int arr[size];
std::ifstream is("data.txt", std::ifstream::in);
if (is)
{
// read into memory
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char *buffer = new char[length];
is.read(buffer, length);
is.close();
// parse into array
std::istringstream iss(buffer);
int i = 0;
while (iss >> arr[i++])
;
delete [] buffer;
// print or use it.
}
return 0;
}
如果你坚持边读边解析,那就重点看我parse into array那一段。
EDIT:
评论说要单独解析第一行,那很容易。
将parse into array 稍作修改:
// parse into array
std::istringstream iss(buffer);
// process first line
std::string headline;
getline(iss, headline);
sscanf(headline.c_str(), "%d %d", &a, &b);// a = 10, b = 10.
// process other part, into array.
int i = 0;
while (iss >> arr[i++])
;
补充称上面这样就行了。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。