使用VS Code编写C++代码时无法使用auto关键字

4
我正在使用VS Code编写C++代码。它表现得非常好。但是每当我在我的代码中使用auto关键字时,程序就无法编译。
例如,如果要迭代字符串,则不使用auto关键字的代码如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("Hello");
    for(int i=0;i<s.length();i++)
    {
        cout<<s.at(i)<<' ';
    }
    cin.get();
}

它编译良好并且运行结果正确。

正在执行任务:g++ -g -o helloworld helloworld.cpp

终端将被任务重用,请按任意键关闭它。

输出:H e l l o

但是,当我尝试使用 auto 关键字来执行同样的任务时,代码如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("Hello");
    for(auto c:s)
    {
        cout<<c<<' ';
    }
    cin.get();
}

但它会产生编译时错误

Executing task: g++ -g -o helloworld helloworld.cpp 

helloworld.cpp: In function 'int main()':
helloworld.cpp:7:14: error: 'c' does not name a type
     for(auto c:s)
              ^
helloworld.cpp:11:5: error: expected ';' before 'cin'
     cin.get();
     ^
helloworld.cpp:12:1: error: expected primary-expression before '}' token
 }
 ^
helloworld.cpp:12:1: error: expected ')' before '}' token
helloworld.cpp:12:1: error: expected primary-expression before '}' token
The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it. 

请帮助我解决问题。


2
如果您使用的GCC版本低于6,则它不会默认使用较新的C++标准版本,您需要明确告诉编译器应启用这些功能(如前面提到的使用-std=c++11选项)。 - Some programmer dude
1个回答

5
这是提示:

执行任务:g++ -g -o helloworld helloworld.cpp

我怀疑你需要使用-std=c++11或更高版本进行编译。
旧版本的gcc/g++将默认使用在auto关键字引入之前的C++ 98标准。可能还有其他配置也是这样默认的。解决方法很简单。
配置你的构建,使得被编译的任务如下:
g++ -std=c++11 -g -o helloworld helloworld.cpp 

如果可用,您还可以使用-std=c++14-std=c++17


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接