2017-10-17 149 views
0

我有這樣的代碼:省略換行符在讀取文件與C++

#include <iostream> 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::ifstream path("test"); 
    std::string separator(" "); 
    std::string line; 
    while (getline(path, line, *separator.c_str())) { 
     if (!line.empty() && *line.c_str() != '\n') { 
      std::cout << line << std::endl; 
     } 

     line.clear(); 
    } 

    return 0; 
} 

文件「測試」被填充有數字,通過各種數目的空格分隔。我只需要閱讀數字,一個接一個,省略空格和換行符。此代碼省略了空格,但不包含換行符。

這些都是從輸入文件「測試」幾行字:

 3  19  68  29  29  54  83  53 
    14  53  134  124  66  61  133  49 
    96  188  243  133  46  -81  -156  -85 

我認爲問題是,這*line.c_str() != '\n'不是確定字串line命中換行符和程序保留打印的正確方法換行符!

這一個偉大的工程:

#include <iostream> 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::ifstream path("test"); 
    std::string separator(" "); 
    std::string line; 
    while (getline(path, line, *separator.c_str())) { 
     std::string number; 
     path >> number; 
     std::cout << number << std::endl; 
    } 

    return 0; 
} 
+0

而不是'* line.c_str()=「\ n''你應該檢查該行不僅包含空格。很難說,沒有看到輸入的例子(請把它做出來,這樣我們可以看到'\ n''字符在哪裏)。 – user0042

+1

你只是檢查第一個字符是換行符。如果一個數字在行的末尾,換行符將是'line'的最後一個字符,而不是第一個字符。 – Barmar

+2

爲什麼不使用'path >> number;',它將跳過任何空格並讀取一個數字。 – Barmar

回答

1

使用流運算符>>閱讀整數:

std::ifstream path("test"); 
int number; 
while(path >> number) 
    std::cout << number << ", "; 
std::cout << "END\n"; 
return 0; 

這將列出所有的整數中的文件,假設他們用空格隔開。

getline的正確用法是getline(path, line)getline(path, line, ' ')其中最後一個參數可以是任何字符。

*separator.c_str()在這種情況下轉換爲' '。不建議使用此用法。

同樣*line.c_str()指向line中的第一個字符。爲了找到最後一個字符用

if (line.size()) 
    cout << line[size()-1] << "\n"; 

當使用getline(path, line)line將不包括最後\n字符。

這是getline的另一個例子。我們讀取該文件逐行,然後每行轉換爲stringstream,然後從每行讀取整數:

#include <iostream> 
#include <string> 
#include <fstream> 
#include <sstream> 

int main() 
{ 
    std::ifstream path("test"); 
    std::string line; 
    while(getline(path, line)) 
    { 
     std::stringstream ss(line); 
     int number; 
     while(ss >> number) 
      std::cout << number << ", "; 
     std::cout << "End of line\n"; 
    } 
    std::cout << "\n"; 
    return 0; 
} 
1

使用內置到C++的isdigit功能。

+0

此功能是否考慮到符號? – Pekov

+0

不,但你可以隨時進行測試,isdigit只會過濾非數字號碼。 – Lavevel