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

标签 c++ c++11 visual-studio-code c++14

我正在使用 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();
}

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

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

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

OUTPUT : 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. 

请帮帮我。

最佳答案

这是线索:

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

我怀疑您需要使用 -std=c++11 或更高版本进行编译。

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

配置您的构建,使正在编译的任务是这样的:

g++ -std=c++11 -g -o helloworld helloworld.cpp 

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

关于c++ - 在 C++ 中编码时无法在 VS Code 中使用 auto 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57035634/

相关文章:

c++ - 封闭类的当前对象的概念

c++ - 在 C++ 中使用函数指针映射枚举键和值

visual-studio-code - VS Code 智能感知的方式

css - 在浏览器中预览 VS 代码中的 Markdown

c++ - 如何为 IE 编译和构建这个 BHO?

c++ - 是否可以使用不在 header 中的 C++ 库代码?

c++ - 在 C++ 中通过递归打印数组

c# - 映射平台特定的互操作类型

java - 在模板类中使用 <limits.h>> 中的最大值

c# - 在 Visual Studio Code 中编写单元测试