Home > Software engineering >  How do I check whether an index of array is empty and then, if it is, skip to the next?
How do I check whether an index of array is empty and then, if it is, skip to the next?

Time:07-12

I'm trying to build a program that can register a user to the database (still learning cpp, I hope that in the near future I'll be able to work with database).

What I'm trying to do with this code is to check whether an index of array is empty for the user to store an ID in it. If it isn't empty, I want the program to keep looking for an empty index of array, for the new info to be stored in.

Here is the code:

void registro() {
std::string userid[3];
userid[0] = "Houkros"; // eventually I'll try to have this being read from a file or server database..
std::string userpass[3];
std::string usermail[3];
std::string userkey[3];
std::string getUid[3];
std::string getUpass[3];
std::string getUmail[3];
std::string getUkey[3];

std::cout << std::endl << " >>>> REGISTRATION <<<< " << std::endl;
std::cout << " =============================================== " << std::endl;
std::cout << std::endl;
std::cout << "Please, enter the desired user id: " << std::flush;
if (userid[0].empty())
{
    std::cin >> userid[0];
}
else {
    std::cin >> userid[1];
}
for (int i = 0; i < 2; i  )
{
    std::cout << " Element of array: " << i << " is > " << userid[i] << std::endl;
}

CodePudding user response:

Please consider the following definitions for an "empty" array element:
a) not initialised (unhelpful, cannot be checked)
b) never yet written to (same as a) )
c) contains "" (possible, but means that "" must not be accepted as an actual content)
d) is empty according to a second array in which that info is maintained (this is what I almost recommend)
e) contains a struct with a string and a maintained "empty" flag (this I recommend)

Whatever you do, make sure that you init all variables and array elements before first read-accessing them; i.e. in all cases first write something meaningful to it.

  • Related