C++ 将字符串转换为字符数组
我犯了这个错误 从字符串常量到C++ 将字符串转换为字符数组,c++,C++,我犯了这个错误 从字符串常量到char* 如何将字符串放入char数组中。以下是我尝试过的: char result[]; result = "invalid"; 编辑: 这就是我想做的 bool intToRoman (int val, char result[]) { MAIN BODY result = "MMM"; } 在这个函数中,我尝试将一个整数转换成一个罗马数字。在我的主体中,我想将字符串(例如“MMM”)存储到我的字符数组结果中。您需要初始化数组: char re
char*
如何将字符串放入char数组中。以下是我尝试过的:
char result[];
result = "invalid";
编辑:
这就是我想做的
bool intToRoman (int val, char result[])
{
MAIN BODY
result = "MMM";
}
在这个函数中,我尝试将一个整数转换成一个罗马数字。在我的主体中,我想将字符串(例如“MMM”)存储到我的字符数组结果中。您需要初始化数组:
char result[] = "invalid";
这将创建一个大小为8的字符数组
但是您最好使用std::string
:
std::string result("invalid");
如果计划在运行时对其进行更改,则可以使用以下任何选项:
char result[] = "invalid"; // 8 bytes in the stack
static char result[] = "invalid"; // 8 bytes in the data-section
const char result[] = "invalid"; // 8 bytes in the stack
static const char result[] = "invalid"; // 8 bytes in the data-section
const char* result = "invalid"; // 8 bytes in the code-section, and a pointer (4 or 8 bytes) in the stack
static const char* result = "invalid"; // 8 bytes in the code-section, and a pointer (4 or 8 bytes) in the data-section
如果您不打算在运行时对其进行更改,则可以使用以下任何选项:
char result[] = "invalid"; // 8 bytes in the stack
static char result[] = "invalid"; // 8 bytes in the data-section
const char result[] = "invalid"; // 8 bytes in the stack
static const char result[] = "invalid"; // 8 bytes in the data-section
const char* result = "invalid"; // 8 bytes in the code-section, and a pointer (4 or 8 bytes) in the stack
static const char* result = "invalid"; // 8 bytes in the code-section, and a pointer (4 or 8 bytes) in the data-section
如果希望仅在运行时的稍后时间对其进行初始化:
char result[] = "invalid"; // 8 bytes in the stack
static char result[] = "invalid"; // 8 bytes in the data-section
...
strcpy(result,"MMM");
// But make sure that the second argument is not larger than the first argument:
// In the case above, the size of "MMM" is 4 bytes and the size of 'result' is 8 bytes
因为这是C++:
std::string结果(“无效”)代码>分配??您的情况下不能使用std::string
?strncpy()
?再次:使用std::string
,让您的生活更轻松@user3229707“我必须使用char”,然后使用strncpy()
和库中所有的东西,不要要求任何东西!去看看你的课程课本吧…@Borgleader谢谢。总有一天我会学会打字的。这不是我的本意。我试图声明一个数组,后来代码主体中有人在我的数组中添加了“无效”一词。@user3229707但您最好使用std::string@user3229707然后您需要声明一个大小正确的数组,稍后再填充它。这很容易出错,但您不必担心,因为您只需使用std::string
@user3229707即可。为什么?这似乎是个糟糕的主意。但是无论如何,声明一个足够大的char
数组,然后使用strncpy
将一个字符串复制到其中。k谢谢,这里还可以问你另一个问题。如果我有一个字符串roman=“MMM”。我如何将罗马语中的内容放入结果@πάνταῥεῖ: 我有一种感觉,那一定会让我发笑,尽管我不确定那是什么问题…@user3229707:strcpy(result,roman)
(如果你喜欢,请接受上面的答案)@barakmanos一个不错的建议:更喜欢使用strncpy()
而不是strcpy()
。