【发布时间】:2011-05-23 19:22:09
【问题描述】:
在我的程序中,我通过 iostream 获得输入:
char input[29];
cin >> input;
我需要使用这个输入作为这个类的一个参数,这个参数作为它的构造函数
class::class(const char* value) {
/* etc */ }
知道如何转换吗?
谢谢
【问题讨论】:
标签: c++ pointers constructor char
在我的程序中,我通过 iostream 获得输入:
char input[29];
cin >> input;
我需要使用这个输入作为这个类的一个参数,这个参数作为它的构造函数
class::class(const char* value) {
/* etc */ }
知道如何转换吗?
谢谢
【问题讨论】:
标签: c++ pointers constructor char
您应该能够将input 作为参数传递给您的构造函数。 char[] 将衰减为 char *,与 const char * 兼容。
但是:流式传输到固定长度的缓冲区是一个非常糟糕的主意(如果有人提供的输入长度超过 28 个字符怎么办?)。请改用std::string(如@George 的回答)。
【讨论】:
string tmp;
cin >> tmp;
foo(tmp.c_str());
【讨论】:
String => string ... 你还应该解释为什么这是一个比 OP 更好的代码。
>> 操作符无法知道它只能读取 29 个字节。
所以你必须明确指定它:
char input[29] = { 0 }; // note sets all characters to '\0' thus the read will be '\0' terminated.
cin.read(input, 28); // leave 1 byte for '\0'
您也可以使用标准字符串。
std::string word;
cin >> word; // reads one space seporated word.
Class objet(word.c_str()); // Or alternatively make you class work with strings.
// Which would be the correct and better choice.
如果你需要阅读整行而不是一个单词
std::string line;
std::getline(std::cin, line);
Class objet(line.c_str()); // Or alternatively make you class work with strings.
// Which would be the correct and better choice.
请注意,在上述所有内容中,您应该在读取后真正检查流的状态,以确保读取正常。
std::string word;
if (cin >> word) // using the if automatically checks the state. (see other questions).
{
Class objet(word);
}
【讨论】: