C++ ‘;pos’;未在此范围中声明

C++ ‘;pos’;未在此范围中声明,c++,visual-studio,C++,Visual Studio,当前正在获取此错误: main.cpp: In function ‘std::string class_name(const std::type_info&)’: main.cpp:43:45: error: ‘pos’ was not declared in this scope if (const size_t pos = name.find(prefix)); pos != string::npos) 我一直试图搞乱这个字符串,但在尝试编译时似乎无法使它通过 守则: #inc

当前正在获取此错误:

main.cpp: In function ‘std::string class_name(const std::type_info&)’:
main.cpp:43:45: error: ‘pos’ was not declared in this scope
  if (const size_t pos = name.find(prefix)); pos != string::npos)
我一直试图搞乱这个字符串,但在尝试编译时似乎无法使它通过

守则:

#include <string>
#include <map>
#include <array>
#include <vector>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <typeinfo>

using namespace std;

void horizontal_line(size_t n = 80)
{
    cout << endl << string(n, '-');
}

void pause(size_t n = 80)
{
    horizontal_line(n);
    cout << "\n[Enter] to continue.";
    cin.get();
}

string currency(const float& amount)
{
    ostringstream ss;
    ss.imbue(std::locale(""));
    ss << showbase << put_money(amount * 100);
    return ss.str();
}

string class_name(const type_info& typeinfo)
{
    static const string prefix("class ");
    static const size_t length = prefix.size();

    string name(typeinfo.name ());
    if (const size_t pos = name.find(prefix)); pos != string::npos)
    name.erase(pos, length);
    return name;
}


#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
空心水平线(尺寸n=80)
{

cout您在if后面有一个分号。因此,第二次出现pos时,它不在if块中,而if块是pos在作用域中的唯一位置。

如果我正确理解您的代码,这可能就是您的意图:

size_t pos = name.find(prefix);

if(pos != string::npos)
    name.erase(pos, length);

您试图在
if
语句中声明和初始化
pos
时使用的语法:

if(const size\u t pos=name.find(prefix));pos!=string::npos)
仅在C++17及更高版本中有效。此外,在需要删除的
之前有一个错误的
,正确的语句是:

if(const size\u t pos=name.find(前缀);pos!=string::npos)

对于C++的早期版本,需要将代码< > POS < /代码>从<代码>中分离出来,如果语句:

const size\u t pos=name.find(前缀);
if(pos!=字符串::npos)
或者,您可以在
if
语句中执行
pos
赋值,而不是声明,但是语法略有不同:

size\u t pos;
if((pos=name.find(prefix))!=string::npos)

if(const size\u t pos=name.find(前缀));pos!=string::npos)
在posI之前,如果我去掉它,我会遇到其他错误,它预计;之前)posI甚至没有考虑好C++17的特性来将作用域保持在最小。很明显,这才是OP真正想要的。