gpt4 book ai didi

c++ - 使用 noskipws 读取文件?

转载 作者:行者123 更新时间:2023-11-28 04:02:46 24 4
gpt4 key购买 nike

我的方法是否正确读取包含空格和换行符 (\n) 的 .txt 文件?我编写程序的说明还要求我检测空格和换行符,以便可以对它们进行操作。

char word_from_file;
ifstream input_file;
input_file.open (*recieved_file_name+".txt");
if (input_file.good() && input_file.is_open())
{
while (!input_file.eof())
{
input_file >> noskipws >> word_from_file;
if (*recieved_choice==1)
{
cout << *recieved_key;
encrypt (recieved_file_name, &word_from_file, recieved_key);
}
}
input_file.close();
}

最佳答案

您的代码是正确的,因为它读取了空格和换行符,但是输入错误检查的位置不正确,这可以通过使用 istream::get() 来缩短。

char word_from_file;
while (input_file.get(word_from_file)) {
if (*recieved_choice == 1) {
cout << *recieved_key;
encrypt (recieved_file_name, &word_from_file, recieved_key);
}
}

istream::get() 从流中读取一个未格式化的字符,因此它会自动读取空格和换行符。

也无需检查文件是否打开或手动关闭它。该文件将在其创建范围的末尾自动关闭,如果文件未打开,则任何尝试的输入操作都是空操作。

关于c++ - 使用 noskipws 读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59237138/

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