我对C++的编码非常陌生,几乎没有任何经验。我的问题是:我想使用字符串,所以我在代码中添加了#include,但是VSCode告诉我identifier "string" is undefinedC/C++(20)。我所做的是添加和修改一个c_cpp_properties.json文件vor VSCode:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"/usr/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu17",
"cppStandard": "gnu++14",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}但这并没有解决问题。另外,我已经确保安装了C++,包括g++编译器。在VSCode中,我使用以下C++插件/加载项: C/C++和C/C++项目生成器(我并不真正使用)。这是我代码的相关部分:
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
string s;
return 0;
}这是错误日志/调试消息:
g++ -std=c++17 -Wall -Wextra -g -Iinc -c src/main.cpp -o src/main.o
src/main.cpp: In function ‘int main(int, char**)’:
src/main.cpp:30:2: error: ‘string’ was not declared in this scope
30 | string s;
| ^~~~~~
src/main.cpp:30:2: note: suggested alternatives:
In file included from /usr/include/c++/9/iosfwd:39,
from /usr/include/c++/9/ios:38,
from /usr/include/c++/9/ostream:38,
from /usr/include/c++/9/iostream:39,
from src/main.cpp:1:
/usr/include/c++/9/bits/stringfwd.h:79:33: note: ‘std::string’
79 | typedef basic_string<char> string;
| ^~~~~~
In file included from /usr/include/c++/9/bits/locale_classes.h:40,
from /usr/include/c++/9/bits/ios_base.h:41,
from /usr/include/c++/9/ios:42,
from /usr/include/c++/9/ostream:38,
from /usr/include/c++/9/iostream:39,
from src/main.cpp:1:
/usr/include/c++/9/string:67:11: note: ‘std::pmr::string’
67 | using string = basic_string<char>;
| ^~~~~~解决方案:将string s;替换为std::string s;。
发布于 2022-05-16 19:38:00
C++字符串在std命名空间中“隐藏”。因为这一点,编译器无法识别string。
您可以包含整个std命名空间:
using namespace std;对特定的字符串执行此操作,而不执行任何其他操作:
using std::string;或在初始化字符串时键入std::string而不是string。默认情况下,C++标准库在编译器的包含路径中,您不需要做任何额外的事情就可以使用它的头部。
https://stackoverflow.com/questions/72264621
复制相似问题