2010-12-03 68 views
0

文本文件看起來像這樣:轉換從Java到C++讀取文件,並解析

Apple,Itunes,1,7.3 
Microsoft,Windows Media Player,1,10 

....等等.....

解析方法是:

private IApplication parseLineToApp(String lineFromTxtFile) { 
    Scanner lineScanner = new Scanner(lineFromTxtFile); 
    lineScanner.useDelimiter(","); 

    return new Application(lineScanner.next(), lineScanner.next(), lineScanner.nextInt(), lineScanner.next()); 
} 

我想在C++中做同樣的事情來創建一個新的應用程序()。 注:我已經有一個應用程序類,並需要嚮應用程序添加到資料庫是應用

感謝提前:)

回答

1

您可以使用Boost創建一個字符串矢量和STL集合。

// given std::string lineFromTxtFile 
std::vector<std::string> scanner; 
boost::split (scanner, lineFromTxtFile, boost::is_any_of(",")); 

return new Application (scanner[0], scanner[1], scanner[2], scanner[3]); 

如果你想scanner[2]是一個整數,有

boost::lexical_cast<int> (scanner[2]) 
+0

我怎樣才能得到一個參考線? – 2010-12-03 18:55:21

+0

@Jon哪一行? – chrisaycock 2010-12-03 19:00:44

0

有一個在C++標準庫沒有掃描儀類,直接翻譯是不可能的。當然,你總是可以實現你自己的。

唉,你可以創建一個分割功能:

unsigned int split(const std::string &txt, std::vector<std::string> &strs, char ch) 
{ 
    size_t pos = txt.find(ch); 
    size_t initialPos = 0; 
    strs.clear(); 

    if (pos != std::string::npos) { 
     // Decompose each statement 
     strs.push_back(txt.substr(initialPos, pos - initialPos + 1)); 
     initialPos = pos + 1; 

     pos = txt.find(ch, initialPos); 
     while(pos != std::string::npos) { 
      strs.push_back(txt.substr(initialPos, pos - initialPos + 1)); 
      initialPos = pos + 1; 

      pos = txt.find(ch, initialPos); 
     } 
    } 
    else strs.push_back(txt); 

    return strs.size(); 
} 

然後,你可以重寫你的代碼爲:

std::vector<std::string> scanner; 
split(lineFromTxtFile, scanner, ','); 

return new Application (scanner[0], scanner[1], scanner[2], scanner[3]); 

希望這有助於。

0

在C/C++中可以通過幾種不同的方式完成文件操作。 A C++ - 風格的方法可以如下所示:

std::vector<Application> ApplicationList; 

std::ifstream fin("myapplist.txt"); // open a file stream 
while (!fin.eof()) // while this isn't the end of the file 
{ 
    char buffer[256] = {0}; 
    fin.getline(buffer, 256); // read the current line of text into the buffer 
    std::vector<std::string> scanner; 
    boost::split(scanner, buffer, boost::is_any_of(",")); // split the buffer and store the results in the scanner vector 
    ApplicationList.push_back(Application(scanner[0], scanner[1], scanner[2], scanner[3]); // add the application to the application list 
} 
fin.close(); 

假設你的應用程序結構/類是可複製(否則你會想在你的ApplicationList使用指針)。