我正在使用 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/