Hoan Dang
Hoan Dang

Reputation: 2280

confusing when concat string in c++

I just try to test how to split word in C++ but I faced with very unknown error. This problem really drives me insane, I don't know why it happens.

This is my code:

std::string key = "hello world";
std::string word = "";

for (int i = 0; i < (int)key.length(); i++)
{
    if (std::isspace(key[i]) || key[i] == '\0')
    {
        std::cout << word << "\n";
        word.clear();
    }
    else
        word += key[i];
}

The result is just only "Hello", I tried to debug and figure out why the word stop concating after the isspace condition? So could anyone please point me the correct direction?

Thanks

Edited: Tried the following, and now its missing the letter d in the end?

    if (std::isspace(key[i]) || key[i + 1] == '\0')
    {

Edit 2: Solved with this:

    if (std::isspace(key[i]) || key[i + 1] == '\0')
    {
        if (key[i + 1] == '\0')
            word += key[i];

Upvotes: 0

Views: 162

Answers (2)

Loki Astari
Loki Astari

Reputation: 264351

Why it is not working

Because this condition is never met:

key[i] == '\0'

Because j is always less than key.length() and (theoretically) the '\0' character is supposed to be at key[key.length()] you never reach it and thus don't print out the second word.

Of you change key to:

std::string key = "hello world again";

You will see it print

hello
world

But it will not print again.

Looking at it from a C perspective

C-String (not C++ std::string) is terminated with '\0'
So if you want to continue down the current path and look for the '\0' character you need to use C-Strings.

To do this you could change the for() so that j is <= to key.length(). But be careful C++ std::string is not like a C-String. The character at key[key.length()] is not valid and you are not allowed to access it. What you should do is convert the C++ std::string into C-String with c_str().

    char tmp = key.c_str()[j];
    if (std::isspace(tmp) || tmp == '\0')

Alternatively

You can just print word after the loop (if it is not empty)

std::string key = "hello world";
std::string word = "";

for (int j = 0; j < (int)key.length(); j++)
{ 

     if (std::isspace(key[j]) || key[i] == '\0')
     {
           std::cout << word << "\n";
           word.clear();
     }
     else
           word += key[j];
}
if (!word.empty())
{    std::cout << word << "\n";
}

Upvotes: 3

Mat
Mat

Reputation: 206679

key[j] == 0 will never happen, the string length doesn't count the terminating 0, so the last word won't ever be printed out.

Remove that test, and add a second std::cout << word after the loop.

Upvotes: 3

Related Questions