Search code examples
c++charc-stringschararray

Char array gets cleared after function gets() on C++


I'm trying to learn C++. Sometimes I get confused by C style strings and its functions. I've been using

char var[1];
fflush(stdin);
gets(var);

to write a string into a char array. I don't know if thats the most efficient way but thats how I've been taught.

Now, I'm making a console program in which I read some variables that way and make things with them. It's all working fine but I have a char array, estudios[1] and I have to compare it with strcmp (I'm not talking about the strcmp(estudios, "N") != 0 I wrote below) to a specific value and i found that te result of the comparation was always the same no matter the value estudios had. I realized that after this chunk of code:

if (strcmp(estudios, "N") != 0){
    cout << "Estudios completos o incompletos?" << endl;
    fflush(stdin);
    gets(indicador);
}

Let's say that the value of estudios is "P". Before the code i showed the value of estudios is "P" but after it it changes it value to "". To be more precise it changes after the gets(indicator); Why does that happen? Is it supposed to do that? Sorry for such a newbie question


Solution

  • Don't use gets. It is dangerous. It shouldn't be used at all. It has been removed from both C and C++ standards. Don't use gets.


    I have a char array, estudios[1]

    strcmp(estudios, "N") != 0
    

    A character array of length 1 can only contain the null terminated string of length 0. The string "N" contains two characters: 'N' and '\0' which is the null termination character.

    If estudios[0] is anything other than the null termination character, then it doesn't contain a null terminated string, and passing it to strcmp will violate the pre-conditions of the function and the behaviour of the program will be undefined.

    Why does that happen?

    The behaviour of the program is undefined.

    Is it supposed to do that?

    You aren't supposed to pass non-null-terminated strings into strcmp.


    Here is a fixed program that probably does what you're trying to do (your example is incomplete, so I'm guessing):

    std::string indicator;
    char c;
    std::cin >> c;
    if (c != 'N') {
        cout << "Estudios completos o incompletos?" << endl;
        std::cin >> indicador;
    }