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

C++ String - Out of scope error

本文关键字:范围 错误 字符串 C++      更新时间:2023-10-16

我试图在我正在编写的 Hangman 程序中玩弄字符串,但无法让它们工作,所以尝试在更简单的基础上使用它们,但我仍然没有运气。

据我在网上阅读的参考资料以及其他人所说的,这段代码应该可以工作:

#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int main (int argc, char** argv){
  string word = {"Hello"};
  int length = strlen(word);
}

但是我收到此编译器错误:

在此范围内未声明"字符串"

因此,"词"也没有在范围内声明。

谁能看出我做错了什么?如果这有所作为,我正在 Ubuntu 上使用 g++ 编译器,但不知道是哪个版本。

你混淆了C和C++。

您只包含 C 库,而std::string来自 C++ 标头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();
}

在此范围内未声明"字符串"

您需要包含标头<string>并将其称为 std::string 。此外,strlen不理解std::string或任何用户定义的类型,但您可以改用 size() 方法:

#include <string>
int main()
{
  std::string word = "Hello";
  size_t length = word.size();
}

<cstring> 是C++支持 C 样式的 null 终止字符串的标头。您应该包括<string> .

您尚未在项目中包含C++字符串标头。

#include <string>

您包含的库都是纯 C 标头。

此外,strlen()不适用于 c++ 字符串;您应该改用word.size()

string是标准类std::basic_string的专业化。它在标头 <string> 中声明

所以如果你想"玩弄标准类std::string:",你需要包含指令

#include <string>

标头 <cstring> 与标头 <string> 不同,它包含标准 C 函数(如 strlen )的声明。

但是,将函数strlen应用于类型 std::string 的对象没有任何意义 在这种情况下,编译器将发出错误。

我建议您使用以下代码以查看差异

#include <iostream>
#include <string>
#include <cstring>
int main (int argc, char** argv)
{
   std::string word = "Hello";
   std::string::size_type length = word.length();
   std::cout << "Object word of type std::string has value "
             << word << " with length of " << length
             << std::endl;
   std::cout << "The size of the object itself is " << sizeof( word ) << std::endl; 
   char another_word[] = "Hello";
   size_t another_length = std::strlen( another_word );
   std::cout << "Object another_word of type char [6] has value "
             << another_word << " with length of " << another_length
             << std::endl;
   std::cout << "The size of the object itself is " << sizeof( another_word ) << std::endl; 
}