C++ How to check if char variable is undefined (not initialized)

  • A+
Category:Languages

how can i check if a char variable is empty?
I mean that check with like empty() method with strings, if the string doesn't contain any character stringVar.empty() will result true. How can i check if a char variable doesn't contain a character?
For example, I've a code like this:

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

This code isn't correct and I don't know how to solve in a nice way, i found a little thing that permise me to bypass the problem but it isn't perfect. For the moment I'm using:

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

Is this the only way to check if mychar isn't initialized yet? If there is a possibility to check if mychar isn't initialized yet different from the one above, which functions have I to use?

Update 1

Software aim: In this specific case the program I'm building is aimed to delete every comment in a coding source code file that the user (me cause is for me) submit, so i can't use a special character because it can be present on the file, use /0 is a nice idea but i hope that there are others. When I write //do something with ... in my program i continue to read characters till i find comments and I ignore them while creating the new file without them.
BOM: No, files i tested didn't throw me errors apart that the algorithm is a little bugged, but not the part i asked to you.

 


You can't.

In C++, uninitialised variables have an unspecified value, and it is undefined behavior to read from them in any way, so you won't even be able to check what's in it.

You have three options:

  • Give it a value that you know you won't encounter in your file. A /0 might work in your case.
  • Use a separate boolean variable to track if you've read it once.
  • In C++17, use a std::optional<char>.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: