C++字符串 - 超出范围错误
C++ String - Out of scope error
我试图在我正在编写的 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;
}
- "myClock"未在此范围错误中声明
- 包含来自另一个文件的函数会导致范围错误(openFoam)
- Visual C:命名空间范围错误或晦涩功能?
- 在遍历字符串时,为什么我没有超出范围错误,即使我已经超出了它的长度?
- 此范围错误中未声明如何修复
- 尝试声明函数的局部变量,但得到范围错误
- c ++ to_string未在此范围错误 [Windows + Devcpp 环境] 中声明
- 将文件读取到向量的向量,超出范围错误
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- Eratosthenes C 的筛子 - 内存处的范围错误
- 向量:内存处的范围错误
- 测试完美哈希函数时超出范围错误
- 为什么此代码会给出 Vector 超出范围错误
- 在填充 Arduino 草图时出现范围错误
- 如何修复C++中矢量的"下标超出范围"错误?
- CPP-模板范围错误
- 在此范围错误中未声明函数错误
- C 表达式:向量下标出范围错误线:1733
- 无法在好友函数中实例化类?我没有得到在范围错误中声明
- 带有类的嵌套结构.范围错误