C++ 字符串 - 超出范围错误

标签 c++ string

我试图在我正在编写的 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/

相关文章:

c - 在 C 中查找字符串中的字符

python - 字符串 append 问题 - python

c++ - 逻辑/关系表达式优化

c++ - (Qt) QNetworkAccessManager 减慢其他应用程序

c++ - 用仿函数检查 vector 的每个元素

c++ - 什么 Linux 库支持套接字、ioctl 调用、tuntap 等...?

c - 如何使用 printf 打印字符串而不打印尾随换行符

java - 我们可以向后拆分 Java 字符串吗?

c - 不使用指针反转字符串

c++ - 将 std::complex 值的 boost::multi_array 复制到 mxArray