2012-05-17 74 views
0
1 = 0 0 97 218 
2 = 588 0 97 218 
3 = 196 438 97 218 
4 = 0 657 97 218 
5 = 294 438 97 218 

我有像上面這樣的txt文件。我怎樣才能讀取這個文件中沒有=的整數?如何通過跳過=來從txt文件中讀取整數?

+0

那是一個有點技術含量低:( –

+0

@NominSim我創建ifstream的一個循環,但是,當它讀取=發生了問題,但我不明白 – droidmachine

+0

@droidmachine:。展示你的代碼 – ildjarn

回答

0

以下是基本框架:逐行閱讀和解析。

for (std::string line; std::getline(std::cin, line);) 
{ 
    std::istringstream iss(line); 
    int n; 
    char c; 

    if (!(iss >> n >> c) || c != '=') 
    { 
     // parsing error, skipping line 
     continue; 
    } 

    for (int i; iss >> i;) 
    { 
     std::cout << n << " = " << i << std::endl; // or whatever; 
    } 
} 

要通過std::cin讀取文件,管道將它導入你的程序,如./myprog < thefile.txt

+0

他沒有做任何努力。該網站writemycodeforme.com –

1

另一種可能性是,由於空白分類=一個方面:

class my_ctype : public std::ctype<char> 
{ 
    mask my_table[table_size]; 
public: 
    my_ctype(size_t refs = 0) 
     : std::ctype<char>(&my_table[0], false, refs) 
    { 
     std::copy_n(classic_table(), table_size, my_table); 
     my_table['='] = (mask)space; 
    } 
}; 

然後包括這個小區域設置灌輸你的數據流,然後讀取數字彷彿=是根本不存在:

int main() { 
    std::istringstream input(
      "1 = 0 0 97 218\n" 
      "2 = 588 0 97 218\n" 
      "3 = 196 438 97 218\n" 
      "4 = 0 657 97 218\n" 
      "5 = 294 438 97 218\n" 
     ); 

    std::locale x(std::locale::classic(), new my_ctype); 
    input.imbue(x); 

    std::vector<int> numbers((std::istream_iterator<int>(input)), 
     std::istream_iterator<int>()); 

    std::cout << "the numbers add up to: " 
       << std::accumulate(numbers.begin(), numbers.end(), 0) 
       << "\n"; 
    return 0; 
} 

誠然,它可能不是很合理加起來所有的數字,因爲在每一行的第一個似乎是一個行號 - 這只是一個快速去莫表明我們真的在閱讀數字而沒有額外的「東西」造成任何問題。

+0

+1這是有史以來最好的解決方案:-) –