C Cout如何打印一个char*
c++ how does cout print a char*
在下面的代码中,函数 getName()
返回 char *
。我想(也可以(返回string
。如果cout
只是指向第一个char的指针,如何将其正确打印到控制台?
#include <iostream>
#include <string>
using namespace std;
class Base
{
protected:
int m_value;
public:
Base(int value)
: m_value(value)
{
}
const char* getName() { return "Base"; }
//string getName() { return "Base"; }
int getValue() { return m_value; }
};
int main()
{
Base base(5);
std::cout << "Base is a " << base.getName() << " and has value " << base.getValue() << 'n';
return 0;
}
cout
和朋友认为 char *
是C弦。
如果您希望它打印由指针引用的单个字符,则必须先解释它,因此cout
获取char
类型。或者,由于c弦是一个炭的数组,您可以使用其0 th item。
const char* myString = "Hello";
cout << "string: " << myString << endl
<< "*string: " << *myString << endl
<< "string[0]: " << myString[0] << endl;
给出(在线检查(:
string: Hello
*string: H
string[0]: H
相关文章:
- 如何创建一个 char *[] 变量,以便将其传递给函数
- C Cout如何打印一个char*
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- C :在字符串中找到一个char,然后在先前的char之后找到另一个字符
- 如何从IStream读取一个char数组并将其写入另一个IStream
- 如何在c++中将计算分解为两个double和一个char
- 返回一个 char 数组而不是 const char *
- 将值从一个 char 数组存储到另一个 char 数组
- 如何在 c++ 中的另一个 char 数组中找到一个字符数组
- 如何在C 中创建一个char数组
- 当一个函数可以被赋予一个 char* 或文字字符串时,声明这个函数的正确方法是什么?
- C++使用类从多维向量输出一个char数组
- 如果您使一个char*ptr存储整数变量的地址,会发生什么
- C++将文件的所有字节都获取到一个char数组中
- 为 execvp() 创建一个 char* const *
- 将两个单词读入一个char数组元素
- 使用循环向后打印一个char数组
- 当我使用模板将一个char数组复制到另一个时出现问题
- C++创建一个char*迭代器
- 返回一个char指针(内存泄漏)