C++如何检查char变量是否未定义(未初始化)

M. *_*tri 0 c++ undefined

如何检查char变量是否为空?
我的意思是使用类似empty()方法检查字符串,如果字符串不包含任何字符stringVar.empty()将导致true.如何检查char变量是否不包含字符?
例如,我有一个这样的代码:

// all libraries are included before and code is simplified because it is very long
std::fstream file;
char mychar;

file.open("userselectedfile.txt", std::fstream::in);
if (file.is_open() == true) {
   while (file.eof() != true) {
      // check if mychar is initialized yet (first time that the while execute)
      if (mychar == '') {
         mychar = file.get();
         // do something special beacuse mychar wasn't initialized
         // do something with other files
      } else {
         mychar = file.get();
         // do something else with other files
      }
   }
}
file.close();
Run Code Online (Sandbox Code Playgroud)

这段代码不正确,我不知道如何以一种很好的方式解决,我找到了一个让我绕过问题的小事,但它并不完美.目前我正在使用:

std::fstream file;
char mychar;

file.open("userselectedfile.txt", std::fstream::in);
if (file.is_open() == true) {
   for (int i = 0; file.eof() != true; i++) {
      if (i = 0) {
         mychar = file.get();
      } else {
         mychar = file.get();
      }
   }
}
file.close();
Run Code Online (Sandbox Code Playgroud)

这是检查mychar是否尚未初始化的唯一方法吗?如果有可能检查mychar是否未初始化但与上面的不同,我可以使用哪些功能?

更新1

软件目标:在这个特定情况下,我正在构建的程序旨在删除用户(我的原因是为我)提交的编码源代码文件中的每个注释,因此我不能使用特殊字符,因为它可以是目前在文件上,使用\0是一个很好的主意,但我希望还有其他人.当我//do something with ...在我的程序中写入时,我继续读取字符,直到我找到注释,并在创建没有它们的新文件时忽略它们.
BOM:不,我测试过的文件并没有让我误认为算法有点错误,但不是我问你的部分.

Eti*_*tel 8

你不能.

在C++中,未初始化的变量具有未指定的值,并且以任何方式从它们读取都是未定义的行为,因此您甚至无法检查其中的内容.

你有三个选择:

  • 给它一个你知道在文件中不会遇到的值.一个\0可能适用于您的情况.
  • 使用单独的布尔变量来跟踪您是否已阅读过一次.
  • 在C++ 17中,使用a std::optional<char>.