使用noskipws进行文件阅读?

我的方法是否正确,以读取包含空白和换行符(\ 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();
}
zhuwenjiez 回答:使用noskipws进行文件阅读?

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

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

本文链接:https://www.f2er.com/2953271.html

大家都在问