将文本文件读取为用不同字符分隔的C++值
Reading a text file into C++ values, separated by different characters
我有一个文本文件,其中包含一些数据,我正在尝试将其读取到我的对象中。
这是一个相当简单的格式,包括一个文件名、一对维度值,然后是一个值对列表:
StringFileName
IntWidth IntHeight
IntA:IntB IntA:IntB IntA:IntB
IntA:IntB IntA:IntB IntA:IntB
IntA:IntB IntA:IntB IntA:IntB
例如:
MyFile.txt
3 3
1:2 3:4 4:5
9:2 1:5 2:1
1:5 8:3 4:2
There may be more unrelated text here
到目前为止,我拥有的是:
void OnLoad(char* InputFilename) {
string Filename;
int Width;
int Height;
// open the file
ifstream inputFile(InputFilename);
// get the filename
getline(inputFile, Filename);
cout << "Filename is " << Filename << endl;
// get the width and height
string dataLine;
getline(inputFile, dataLine);
stringstream ss(dataLine);
ss >> Width;
ss >> Height;
cout << "Dimensions are " << Width << "x" << Height << endl;
// get the lines of tile-data
for (int Y = 0; Y < Height; Y++) {
/*
* Here is where I'm getting stuck.
* I have a string of "i:i i:i i:i" values, and I get a series of strings
* of "i:i" values, but can't work out the neatest way of splitting it out.
*/
getline(inputFile, dataLine);
stringstream row(dataLine);
for (int X = 0; X < Width; X++) {
int IntA;
int IntB;
// ?
DoStuffWith(IntA, IntB);
}
}
}
这样的东西应该能在中工作
std::ifstream file("filename");
std::string file_name;
int height, width;
file >> file_name >> height >> width;
// i don't know what your format is but it isn't very importance
std::deque<std::pair<int, int> > pairs;
std::string line;
int i, j;
char a;
while(std::cin >> i >> a >> j) //here i j are values in your pair.
{
if(a!=':') break;
pairs.push_back(std::make_pair(i, j));
}
vector<string> results;
boost::split( results, data_string, boost::is_any_of(" :") ); <- splits on spaces and ":"
然后你就可以把所有的数据放在一个方便的容器里了!
也许对你来说不是最好的解决方案,但记住这一点很好。
使用strtok
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
现在可以使用"*i"并以更干净的方式分配int值。
std::string line;
do{
getline(inputFile,line);
sregex_token_iterator end;
for(sregex_token_iterator i(line.begin(), line.end(), pattern,-1); i!=end;++i)
{
cout<< *i << " " ;
}
}while(!inputFile.eof());
相关文章:
- 在Arduino中将字符串转换为(逗号分隔的十六进制)字符串到无符号字符数组
- 获取带有字符 X 的输入 X/X/etc 并用斜杠 / 分隔它
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- C++:使用't'分隔符分隔字符*
- 用字符分隔数字
- 如何获得一些用空格分隔的字符
- 如果字符串中没有空格,如何解析带有数字和字符的字符串并分隔数字和字符
- 如何在 c++ 中读取带有分隔字符的用户输入,同时保留空格作为输入
- 如何使键盘输入变成一个数组,用字符分隔
- 递增由不同分隔符分隔的字符数组中的数字
- 将文本文件读取为用不同字符分隔的C++值
- 分隔字符串的最佳ASCII字符是什么
- 在C++中打印用新行分隔的6,5,4,3,2个字符
- 从字符串中读取多个数据,使用sstream以字符分隔
- 在无符号字符数组中读取充满字符串(用换行符分隔)的文件(反之亦然)的最快方法是什么?
- 如何从C++中字段由'|'字符分隔的行中提取数据?
- C从竖线字符分隔的文件中读取
- std::getline:分隔字符与字符计数
- 将";"分隔的文件读入字符数组结构
- 如何创建一个字符串数组来拆分字符,其中单词由" "分隔?C++