简体   繁体   English

为什么for循环不断在else语句处停止?

[英]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. for循环在找到空格,逗号或句点后会继续停止。 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. 问题是,即使您从输入中删除了一个字符, i一直在递增。 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. 由于strArray现在有一个孔,因此该孔很可能用0填充,从而结束了C字符串。 PS this behavior is not guaranteed and you might end up with completely different results on another run of the program. PS不能保证此行为,并且您可能在另一次运行程序时得到完全不同的结果。

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: delete()将迭代器返回到已删除元素之后的下一个元素,因此应改用该元素:

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? 您可以张贴为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. for循环中删除++i Put it under the else clause. 将其放在else子句下。

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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