C++:将字符插入字符串
所以我试图将从一个字符串中获得的字符插入到另一个字符串中。 这是我的行动: 1. 我想使用简单的:
someString.insert(somePosition, myChar);
2. 我收到错误,因为插入需要(在我的情况下) char* 或 string
3. 我正在通过 stringstream 将 char 转换为 char*:
stringstream conversion;
char* myCharInsert;
conversion << myChar //That is actually someAnotherString.at(someOtherPosition) if that matters;
conversion >> myCharInsert;
someString.insert(somePosition, myCharInsert);
4. 一切似乎都编译成功,但程序崩溃了获取行
conversion >> myCharInsert;
。
5.我试图用字符串替换char*:
stringstream conversion;
char* myCharInsert;
conversion << myChar //That is actually someAnotherString.at(someOtherPosition) if that matters;
conversion >> myCharInsert;
someString.insert(somePosition, myCharInsert);
一切似乎都很好,但是当someAnotherString.at(someOtherPosition)
变成空格时,程序崩溃。
那么我该如何正确地做到这一点呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::string::insert
。插入单个字符的重载实际上有三个参数:
第二个参数
n
,是将c
插入字符串中位置pos<的次数。 /code> (即重复该字符的次数。如果您只想插入该字符的一个实例,只需将其传递一次,例如,
There are a number of overloads of
std::string::insert
. The overload for inserting a single character actually has three parameters:The second parameter,
n
, is the number of times to insertc
into the string at positionpos
(i.e., the number of times to repeat the character. If you only want to insert one instance of the character, simply pass it one, e.g.,最简单的是为自己提供一个将字符转换为字符串的函数。有很多方法可以做到这一点,例如
然后您可以简单地说:
并在您想要字符串但有字符的其他情况下使用该函数。
Simplest is to provide yourself with a function that turns a character into a string. There are lots of ways of doing this, such as
Then you can simply say:
and use the function in other cases where you want a string but have a char.
问题是您正在尝试取消引用(访问)
myCharInsert
(声明为char*
),它指向到内存中的随机位置(可能不在用户的地址空间内),这样做是未定义的行为(在大多数实现上会崩溃)。编辑
要将
char
插入字符串中,请使用string& insert ( size_t pos1, size_t n, char c );
重载。额外
要将
char
转换为std::string
,请阅读这个答案The problem is that you are trying to dereference(access)
myCharInsert
(declared as achar*
) which is pointing to a random location in memory(which might not be inside the user's address space) and doing so is Undefined Behavior (crash on most implementations).EDIT
To insert a
char
into a string usestring& insert ( size_t pos1, size_t n, char c );
overload.Extra
To convert
char
into astd::string
read this answer您可以尝试:
You can try: