将const char转换为char时出现未处理的异常

Daa*_*sin 1 c++ strcat

在过去的30分钟里,我一直在尝试将const char转换为char.这就是我所拥有的.

 string atr; 

 getline(cin,atr); // Start off with a string because getline takes nothing else.
 const char *buffA = atr.c_str(); // Create a const char of the string converted to a const char.
 char *buff = ""; // Create a new char to hold the converted result.
 strcat(buff,buffA); // Do the conversion.
 parseargs(buff); // Pass the data on.
Run Code Online (Sandbox Code Playgroud)

但是,我得到了一个未处理的异常.我不知道为什么.我只是在控制台中键入'try'作为我唯一的参数.

orl*_*rlp 8

尝试使用C++而不是C语言:

std::vector<char> data(atr.begin(), atr.end());
data.push_back('\0');
parseargs(&data[0]);
Run Code Online (Sandbox Code Playgroud)


Jam*_*nze 5

您的代码有两个问题.首先,char*使用字符串文字初始化a .这使用了弃用的转换; 字符串文字的类型是char const[](转换为char const*,而不是转换为char*),因为任何修改文字的尝试都是未定义的行为.第二个是你的字符串文字只有一个char长,所以即使你可以写它,除非atr是空的,你写的是超出缓冲区的末尾.

你没有告诉我们任何事情parseargs.如果它没有修改它的参数,你可以通过它atr.c_str(),并完成它.(如果它是忽略const的遗留函数,你可能必须在const_cast这里使用.)如果它确实修改了它的参数(比如因为它使用了strtok),那么你必须明确地将a推'\0'到末尾atr,然后传递它 &atr[0].(不是一个特别干净的解决方案,但如果你atr以后不使用它,它应该工作.)