使用noskipws读取文件吗?

问题描述 投票:0回答:1

我的方法读取包含空格和换行符(\ 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();
}
c++ file-handling
1个回答
0
投票

您的代码是正确的,因为它读取空格和换行符,但是输入的错误检查位置不正确,可以使用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()从流中读取未格式化的字符,因此它将自动读取空白和换行符。

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

© www.soinside.com 2019 - 2024. All rights reserved.