gpt4 book ai didi

C++: ifstream::getline 问题

转载 作者:搜寻专家 更新时间:2023-10-31 00:46:48 25 4
gpt4 key购买 nike

我正在读取这样的文件:

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 中保存了我的文件。而且我用linux的cat命令也输出过,最后没有return。所以文件应该没问题。

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

谢谢。

最佳答案

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

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

#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 )

关于C++: ifstream::getline 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com