Home > Net >  C output of string.size() not correct
C output of string.size() not correct

Time:09-05

I wrote the following code:

#include <iostream>
#include <time.h>
#include <string.h>

int main()
{
    std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
    std::string word;

    unsigned long long int i = 0;
    srand(time(NULL));
    while(true)
    {
        int randomIndex = rand() % 27;
        word  = alphabet[randomIndex];

        // If the word might be the desired word, "hi"
        if (word.size() == 2) 
        {
            // The word should only be printed if its length is equal to 2
            std::cout << i << " : " << word << word.size() <<  std::endl;
            if (word == "hi") 
            {
                break;
            }
            else // The word isn't "hi". We reset the variable word and continue looping
            {
                word = "";
            }
            i  = 1;
        }

    }
    return 0;
}

It is supposed to put together random letters until word is equal to "hi". Until that, only 2-character words should be printed, but for some reason the program seems to be thinking that 1-character words have a length of 2. Therefore it also prints 1-character words.

Can anyone please help me?

CodePudding user response:

Let's change the print debug line as follows.

std::cout << randomIndex << '\t' << i << " : " << word << " --> " << word.size() <<  std::endl;

Here, when we check the strings that look like a single character but 2 characters, we come across them in a random number of 26.

The length of the string "abcdefghijklmnopqrstuvwxyz" is 26. Since the indices of the arrays start from 0, they must be in the range of random numbers [0, 25] we produce.

Then let's update the line of code where we generate the random number as follows.

int randomIndex = rand() % 26

In the wrong code, the 26th character corresponds to the memory cell at the end of the string. Let's take a different example to understand.

int main()
{
    char arr[5];
    std::string a = "a";
    a =arr[1];
    std::cout << a << " " << a.size() << '\n'; // 2
    
    a =arr[5];
    std::cout << a << " " << a.size() << '\n'; // 3

    a =arr[6];
    std::cout << a << " " << a.size() << '\n'; // 4
    
    return 0;
}
  •  Tags:  
  • c
  • Related