新手提出的有关删除非Up-alpha的快速问题:为什么我的代码不起作用?

问题描述 投票:0回答:2

嗨,我正在尝试从字符串输入中删除所有未大写的字母,但是我不确定代码中的错误在哪里。如果您知道原因,请发表评论!

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

string CreateAcronym(string userPhrase) {
int i;
int stringSize;
char charAti;

stringSize = userPhrase.size();

for (i=0 ; i < stringSize ; i++ ) {
   charAti = userPhrase.at(i);
   if ( !isupper(charAti)) {
      userPhrase.erase(i,1);
   }
}
return userPhrase;
}

int main() {
string userSentence;

getline(cin , userSentence);

cout << CreateAcronym(userSentence) << endl;

return 0;
}
c++ xcode new-operator
2个回答
1
投票
  • 您缓存了旧的字符串长度,并继续使用,但是通过删除字符将使字符串变短。
  • 由于删除后i++未被取消,因此您要跳过字符以删除字符。
stringSize = userPhrase.size();

for (i=0 ; i < stringSize ; i++ ) {
   charAti = userPhrase.at(i);
   if ( !isupper(charAti)) {
      userPhrase.erase(i,1);
   }
}

应该是

for (i=0 ; i < static_cast<int>(userPhrase.size()) ; ) {
   charAti = userPhrase.at(i);
   if ( isupper(charAti)) {
      i++;
   } else {
      userPhrase.erase(i,1);
   }
}

0
投票

您的代码中有2个问题。首先,您要擦除循环中的字符串(这会更改字符串的长度),但在比较中使用预先计算的长度。其次,在不删除字符时,只需增加i。否则,您将跳过一些字符。一个工作循环是:

for (i = 0; i < userPhrase.size();) {
   charAti = userPhrase.at(i);
   if ( !isupper(charAti)) {
      userPhrase.erase(i,1);
   }
   else {
     ++i;
   }
}

这里是demo

© www.soinside.com 2019 - 2024. All rights reserved.