我有這樣的代碼:省略換行符在讀取文件與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;
}
而不是'* line.c_str()=「\ n''你應該檢查該行不僅包含空格。很難說,沒有看到輸入的例子(請把它做出來,這樣我們可以看到'\ n''字符在哪裏)。 – user0042
你只是檢查第一個字符是換行符。如果一個數字在行的末尾,換行符將是'line'的最後一個字符,而不是第一個字符。 – Barmar
爲什麼不使用'path >> number;',它將跳過任何空格並讀取一個數字。 – Barmar