我试图在我正在编写的 Hangman 程序中使用字符串,但无法让它们工作,所以尝试在更简单的基础上使用它们,但我仍然没有运气。
据我在网上阅读的引用资料以及其他人所说的,这段代码应该有效:
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int main (int argc, char** argv){
string word = {"Hello"};
int length = strlen(word);
}
但是我得到这个编译器错误:
“字符串”未在此范围内声明
因此,'word' 也未在范围内声明。
谁能看出我做错了什么?我在 Ubuntu 上使用 g++ 编译器,如果有区别的话,不知道是哪个版本。
最佳答案
您混淆了 C 和 C++。
您仅包含 C 库,而 std::string
来自 C++ header string
。你必须写:
#include <string>
使用它。但是,您随后必须进行其他更改,例如不使用 strlen
。
你应该从你的 C++ 书中学习,而不是互联网上的随机帖子 (#lolirony)
C 版
#include <string.h>
int main(void)
{
const char* word = "Hello";
const size_t length = strlen(word); // `size_t` is more appropriate than `int`
return 0;
}
类C C++版本
#include <cstring>
using namespace std;
int main()
{
const char* word = "Hello";
const size_t length = strlen(word);
}
地道的C++版本(推荐)
#include <string>
int main()
{
const std::string word = "Hello";
const std::size_t length = word.size();
}
关于C++ 字符串 - 超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855288/