假设一个文件存储数据如下图,现在要把这里面的每个数据都读取出来存到数组里,
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) :
如果还是按照上述方法读取的话,就读取不到所需要的数据(10),大家有什么优雅的方法去解决这一类问题吗(比如100,1000...但都是空格隔开,读出来的格式要是int型的),越简洁越好
伊谢尔伦2017-04-17 11:36:38
讀這種並不大的文件,比較好的習慣是先統一讀到記憶體中,再做解析。由於這個文件格式並不複雜,解析其實非常簡單。
#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++])
;
補充稱上面這樣就行了。
巴扎黑2017-04-17 11:36:38
這種純粹解析的文字並沒有通用的解析方法.但是可以考慮從以下兩個方面來處理:
1. 檔案儲存為二進位格式,定義一個類似於如下的結構體進行進行讀入。
tydefine HEADER {
size_t w;
size_t j;
char *a;
}Header;