2013-06-19 21 views
0

我想寫一個代碼,在閱讀txt文件時會跳過最後一個詞。我不知道如何去輸出而不是,包括最後一行和之前的空格。任何幫助將不勝感激,我是新來的C + +。每行最後的單詞需要跳過?

+0

你的意思是你想讀的線和輸出線文件沒有行的最後一個字? – chris

+0

正是我需要的,謝謝! – user2499401

+0

顯示您已編寫的代碼 – 0decimal0

回答

2

下面是用模擬輸入一個相當簡單的方法:

for (std::string line : {"hello im joe", "abc def", "123", "1 2 3 4 5"}) { 
    auto pos = line.find_last_of(' '); //find last space 

    if (pos == std::string::npos) { 
     continue; //don't print anything if not found 
    } 

    //print substring from beginning to space position 
    std::cout << line.substr(0, pos) << '\n'; 
} 
+0

請注意,上述語法僅適用於您的編譯器支持[基於範圍的循環](http://en.wikipedia.org/wiki/C%2B%2B11#Range-based_for_loop )。 – Anthony

+0

@ anthony-arnold,這只是模擬輸入,因爲Coliru沒有做輸入(它顯示哪些輸入工作很好,雖然)。它可能是'for(std :: string line; std :: getline(std :: cin,line);)'。 – chris

相關問題