当输入 1 个没有空格的名称时,它会显示"std::out_of_range"

When inputting 1 name with no spaces it says 'std::out_of_range'

本文关键字:显示 range std out of 输入 空格      更新时间:2023-10-16

我应该输入一个名称。如果此名称没有空格,我想打印名称,直到它有两个空间,如果它有1个空间,我想再打印姓氏一次。

例如,如果我输入Sara,我会得到此错误:

丢弃'std :: out_of_range'的实例后终止调用 what((:basic_string :: substr:__pos(是1844444444073709551615(> this-"> size(((是4(

int SpaceCounter=0;
for(int i=0;i<=name.length();i++)
{
  if(name[i] == ' ')
  {
    SpaceCounter++;
  }
}
if(SpaceCounter>=2)
{
cout<< name;
}
else if(SpaceCounter=1)
{
    size_t pos = name.find(" ");
    string str3 = name.substr (pos);  
    cout <<name<<str3;
    //break;
}
else if(SpaceCounter=0)
{
  for(int i=0;i<2;i++)
  {
    cout <<name<<" ";
  }
}

我认为您以错误的方式进行操作。找到其他空间时,您可以删除它们。您还应在条件下提防单个=。这是一个更好的版本:(未测试(

void f(const std::string& name) {
    unsigned spaces = 0;
    std::string out;
    for(unsigned i = 0; i < name.length(); i++)
        if(name[i] == ' ') {
            if(spaces == 0)
                // allow one space
                out += name[i];
            spaces++;
        } else 
            out += name[i];
    }
    if(spaces == 0)
        // no spaces found, print 2 times
        std::cout << out << ' ' << out << std::endl;
    else
        std::cout << out << std::endl;
}

问题在这里:

for(int i=0;i<=name.length();i++)

<=更改为<。正如书写一样