3

我正在阅读这样的文件:

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。但随后不是循环结束,而是读取另一个字符串,这似乎是一个返回/换行符。

我已将我的文件保存geditnano. 而且我也用linuxcat命令输出过,最后没有返回。所以文件应该没问题。

为什么我的代码读取返回/换行符?

谢谢。

4

4 回答 4

4

首先让我们确保你的输入文件是好的:

运行以下命令并让我们知道输出:

#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”输出到文件时,它会转换为行终止序列。

编辑 2

所以我有文件: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 )
于 2011-01-16T06:32:52.660 回答
2

这是工作...

#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;
}

输入 file.txt:1 2 3 4 5
答案:12345

于 2011-01-16T06:09:45.160 回答
0

试试这个方法:

while ( !file.eof()  )
{
    file.getline( string, 256, ' ' );
        // handle input
}
于 2011-01-16T06:15:46.167 回答
0

它很旧,但似乎没有适当的解决方案。

我很惊讶没有人注意到他正在使用空格分隔符。因此,不会读取整行,而只会读取第一个空格。因此 getline 在遇到 EOF 之前仍有更多数据要读取。

所以下一个 getline 将读取换行符并返回与分隔符相同的 . 如果 getline 调用是这样的:

文件.getline(字符串,256)

它不会返回换行符,而是一步完成。

于 2020-03-19T04:32:42.687 回答