C++;:表达式:字符串下标超出范围 我用C++中的一个bug来面对一个问题。代码如下:

C++;:表达式:字符串下标超出范围 我用C++中的一个bug来面对一个问题。代码如下:,c++,C++,错误为:表达式:字符串下标超出范围 #include "stdafx.h" #include <iostream> #include <algorithm> #include <string> void removeAllchars1(std::string s) { int len = strlen(s.c_str()); std::string b; int len2 = strlen(b.c_str()); for(int i = 0;

错误为:表达式:字符串下标超出范围

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>

void removeAllchars1(std::string s)
{
  int len = strlen(s.c_str());
  std::string b;
  int len2 = strlen(b.c_str());
  for(int i = 0; i < len; ++i)
  {
    if(isdigit(*(s.c_str()+i)))
    {
      b[len2]=s[i];
      ++len2;
    }
  }
  std::cout <<"\nAfter removeAllchars1 function is:"<< *(b.c_str());
}
#包括“stdafx.h”
#包括
#包括
#包括
void removeAllchars1(标准::字符串s)
{
int len=strlen(s.c_str());
std::字符串b;
int len2=strlen(b.c_str());
对于(int i=0;ilen2
b
的长度(尽管计算方式相当复杂,
b.length()
?)有什么问题),正如错误所说,这超出了范围。如果要将字符附加到字符串中,请执行以下操作:

b += s[i];

嗯……你也要给我们看一些代码吗?此外,包含“尽快”而不是问题的帖子往往会被否决和关闭。
b[len2]
总是访问字符串的末尾。另外,只需使用
s.size()
。你好,托梅克。void removeAllchars1(std::string s){int len stren=strlen(s.c_str());STD::String B;int Le2= StrLon(B.CyString());(In i=0;I sLyString(+)i){{B+= S[i];}:STD::CUH-Hi Mike Seymour B+= S[i];//关于语法C++。//1@NgocPhan:这是因为您正在打印
*(b.c_str())
,这只是第一个字符。请尝试打印
b
。更一般地说,停止调用
c_str()
,除非您确实需要与c兼容的字符串(此函数中的任何地方都不需要)。
b += s[i];