在 C++ 中编码时无法在 VS Code 中使用 auto 关键字

Rah*_*jar 4 c++ c++11 c++14 visual-studio-code

我正在使用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();
}
Run Code Online (Sandbox Code Playgroud)

它编译 find 并运行并给出正确的输出

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

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

输出:你好

但是每当我尝试执行相同的工作但使用 auto 关键字时,代码看起来像

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

但它给出了编译时错误

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. 
Run Code Online (Sandbox Code Playgroud)

请帮帮我。

sel*_*bie 5

这是线索:

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

我怀疑你需要使用-std=c++11或稍后进行编译。

在引入 auto 关键字之前,旧版本的 gcc/g++ 将默认为 C++ 98 标准。可能还有其他配置,这也是默认配置。解决方法很简单。

配置您的构建,使正在编译的任务如下:

g++ -std=c++11 -g -o helloworld helloworld.cpp 
Run Code Online (Sandbox Code Playgroud)

如果可用,您也可以使用-std=c++14或。-std=c++17