gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:49 25 4
gpt4 key购买 nike

如何检查一个char变量是否为空?
我的意思是用类似 empty() 方法检查字符串,如果字符串不包含任何字符 stringVar.empty() 将结果为真。如何检查 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();

这段代码不正确,我不知道如何以好的方式解决,我发现了一些允许我绕过问题的小东西,但它并不完美。目前我正在使用:

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();

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

更新 1

软件目标:在这种特定情况下,我正在构建的程序旨在删除用户(我的原因是为了我)提交的编码源代码文件中的每条评论,因此我可以' 使用特殊字符,因为它可以出现在文件中,使用 \0 是个好主意,但我希望还有其他的。当我在程序中编写 //do something with ... 时,我会继续读取字符,直到找到注释,然后在创建没有注释的新文件时忽略它们。
BOM: 不,我测试的文件并没有给我带来错误,因为算法有点错误,但不是我问你的部分。

最佳答案

你不能。

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

你有三个选择:

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

关于C++如何检查char变量是否未定义(未初始化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901324/

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