简体   繁体   中英

Why does the for loop keep stopping at else statement?

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

main()
{
string str1;
char strArray[80];
cout << "Enter string: ";
getline(cin, str1);

transform(str1.begin(), str1.end(), str1.begin(), ::tolower);

for(int i = 0;i < str1.length();i++)
{
    if(str1[i] == ' ' || str1[i] == ',' || str1[i] == '.')
    {

    }
    else
    {
        strArray[i] = str1[i];
    }
}

cout << strArray;
return 0;
}

The for loop keeps stopping after it finds a space, comma, or period. Could someone explain to me why this is happening?

The problem is that i keeps incrementing even though you erased a character from the input. It's not actually stopping, just skipping a character. Since strArray now has a hole in it, it's likely that the hole is filled with 0 thus ending the C-string. PS this behavior is not guaranteed and you might end up with completely different results on another run of the program.

When you call erase it affects the container, so you need to handle this. erase() returns the iterator to the next element after the deleted one, so you should use that instead:

int i = 0;
for(string::iterator it = str1.begin(); it != str1.end(); )
{
    if(*it == ' ' || *it == ',' || *it == '.') 
    {
        it = str1.erase(it);
    }
    else
    {
        strArray[i++] = *it++;
    }
}
strArray[i] = '\0'; // terminate string

Can you post which string you input for str1? Cause I try run it and it run well without stop. The only proplem I found with your code is that you erase the char in the loop which will lead to wrong result string.

You are erasing characters from the string while still continuing to increment the counter. Remove ++i from the for loop. Put it under the else clause.

for(int i = 0;i < str1.length();)
{
   if(str1[i] == ' ' || str1[i] == ',' || str1[i] == '.')
   {
      str1.erase(i, 1);
   }
   else
   {
      strArray[i] = str1[i];
      ++i;
   }
}
strArray[str1.length()] = '\0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM