gpt4 book ai didi

c++ - 将文本文件读入 C++ 值,由不同的字符分隔

转载 作者:行者123 更新时间:2023-11-27 23:25:45 25 4
gpt4 key购买 nike

我有一个包含一些数据的文本文件,我正在尝试将其读入我的对象。

这是一种相当简单的格式,由一个文件名、一对维度值和一个值对列表组成:

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));
}

关于c++ - 将文本文件读入 C++ 值,由不同的字符分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9634406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com