[英]C++: ifstream::getline problem
我正在閱讀這樣的文件:
char string[256];
std::ifstream file( "file.txt" ); // open the level file.
if ( ! file ) // check if the file loaded fine.
{
// error
}
while ( file.getline( string, 256, ' ' ) )
{
// handle input
}
僅出於測試目的,我的文件只有一行,末尾有一個空格:
12345
我的代碼首先成功讀取了 12345。 但是,它不是循環結束,而是讀取另一個字符串,這似乎是一個返回/換行符。
我已經在gedit
和nano
保存了我的文件。 而且我也用Linux cat
命令輸出過,最后沒有返回。 所以文件應該沒問題。
為什么我的代碼讀取返回/換行符?
謝謝。
首先 leet 確保您的輸入文件是好的:
運行以下命令並讓我們知道輸出:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ifstream file("file.txt");
std::cout << std::hex;
std::copy(std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>(),
std::ostream_iterator<int>(std::cout, " "));
}
輸出為 31 32 33 34 35 20 0A
嘗試運行此代碼,看看輸出是什么:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ofstream file("file.txt");
file << "12345 \n";
}
轉儲此文件的輸出並將其與原始文件進行比較。
問題是不同的平台有不同的線路終止序列。 我只想驗證 '0x0A' 是您平台的線路終止序列。 請注意,當以文本模式讀取文件時,行終止序列會轉換為 '\\n',而在文本模式下將 '\\n' 輸出到文件時,它會轉換為行終止序列。
所以我有文件:file.txt
> od -ta -tx1 file.txt
0000000 1 2 3 4 5 sp nl
31 32 33 34 35 20 0a
0000007
所以該文件包含 1 行以0x0A
結尾
使用這個程序:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ifstream file("file.txt");
std::string line;
while(std::getline(file,line))
{
std::cout << "Line(" << line << ")\n";
}
}
我得到:
> g++ t.cpp
> ./a.out
Line(12345 )
它正在工作......
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream file("file.txt");
int main()
{
string tmp="",st="";
while (!file.eof())
{
file>>tmp;
if (tmp != "") st+=tmp;
tmp="";
}
cout<<st<<endl;
return 0;
}
輸入文件.txt:1 2 3 4 5
答案:12345
試試這個方法:
while ( !file.eof() )
{
file.getline( string, 256, ' ' );
// handle input
}
它很舊,但似乎沒有適當的解決方案。
我很驚訝沒有人注意到他正在使用空格分隔符。 因此,不會讀取整行,而只會讀取到第一個空格。 因此 getline 在遇到 EOF 之前仍然有更多的數據要讀取。
所以下一個 getline 將讀取換行符並返回與分隔符相同的 . 如果 getline 調用是這樣的:
file.getline(字符串,256)
它不會返回換行符,並將一步完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.