簡體   English   中英

將文本文件讀取為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));
}

Boost的split函數可以任意划分多個謂詞。 因此,您可以執行以下操作:

vector<string> results;
boost::split( results, data_string, boost::is_any_of(" :") ); <- splits on spaces and ":"

然后,將所有數據保存在一個方便的容器中!

也許這不是您所需要的最佳解決方案,但是請牢記這一點。

現在,您可以使用“ * 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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM