【问题标题】:What's the error within this code?这段代码有什么错误?
【发布时间】:2015-03-01 19:08:46
【问题描述】:

当我尝试构建此代码时,它会显示错误! 也不知道怎么解决!!

错误 C3531:“x”:类型包含“auto”的符号必须具有初始化程序
错误 C2143:语法错误:在 ':' 之前缺少 ','

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <cctype>
using namespace std;

   int main(){
ifstream in("input.txt");
ofstream out("output.txt");
string s;
int line=0;
vector<string> vec(1,"dummy");
multimap<int,int> M;

while(getline(in, s)){
    line++;
    vec.push_back(s);
    if(line%12==10){
        string temp="";
        for(auto x:s) if(isdigit(x)) temp+=x;
        int key = stoi(temp);
        M.insert(make_pair(key,line));      
    }
}

auto it = M.rbegin();
while(it != M.rend()){      
    int i = it->second;
    int start = (int(i/12))*12 +1;
    for(int j=1; j<=12; j++) out << vec.at(start++) << "\n";        
    it++;
}


in.close();
out.close();    
return 0;
}

【问题讨论】:

  • 您使用的是什么版本的 Visual Studio?看起来它不支持基于范围的for
  • 现在是 2010 年?!!那我怎么解决呢?!
  • 升级到 VS2012 或更高版本。或者停止使用基于范围的for 循环
  • @Kurd 不,今年是 2015 年
  • 正如 Praetorian 所说,基于范围的 for 循环仅在 VS2012 及更高版本中实现。如果您不必使用 VS,g++(版本 >= 4.7)支持它们。

标签: c++


【解决方案1】:

由于VS2010不支持该语法,就使用pre-c++11的语法:

if(line%12==10){
    string temp="";
    for (std::string::const_iterator iter=s.begin(); iter!=s.end(); ++iter)
        if (isdigit(*iter)) temp += *iter;
    int key = stoi(temp);
    M.insert(make_pair(key,line));      
}

或者也许:

if (line%12 == 10) {
    int key = 0;
    for (std::string::const_iterator iter=s.begin(); iter!=s.end(); ++iter)
        if (isdigit(*iter)) key = (key * 10) + (*iter - '0');
    M.insert(make_pair(key, line));
}

并摆脱临时字符串和stoi

【讨论】:

    【解决方案2】:

    MS VC++ 2010 不支持基于范围的 for 循环的标准语法。但它支持以下语法:

    for each (auto x in s) if(isdigit(x)) temp+=x;
    

    因此这是编译错误的原因。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多