如何将char扩展到字符串的末尾 [英] how to strcat a char to the end of a string

查看:103
本文介绍了如何将char扩展到字符串的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来很简单,而且极大地困扰着我.如何将一个char串联到cstyle字符串的末尾?这说明了我的问题:

this seems simple, and it''s bugging me immensely. how do you concatenate just a char onto the end of a cstyle string? this illustrates my issue:

char meh[100];
char letter = (char) i+32;
strcat(meh, letter);  
// won't work



和:



and:

char meh[100]
meh[strlen(meh)] = (char) i+32;
meh[strlen(meh) + 1] = '\NUL';  
// works, but for some reason, the null termination won't work and the string is now unbounded and contains a bunch of garbage



我在这里想念一些愚蠢的东西,有人在乎指出吗?顺便说一句,我只是以前使用的变量.只是知道char变量不是常数,所以我可以改成char * meh ="p",因为char每次运行都不同.所以我必须在字符串上获取一个char变量,除非有其他怪异的方法将其转换为c字符串.



i''m missing something stupid here, anyone care to point it out? btw, i is just a variable used previously. just know that the char variable isn''t some constant, that i can instead just go char * meh = "p", because the char is different every run. so i have to get a char variable onto the string, unless there is some other weird way to cast it as a c-string.

推荐答案

为什么要这么做?

字符的串联实际上意味着将字符写到当前最后一个字符之后的地址.您还需要在下一个位置写空:

Why doing all that?

Concatenation of a char really means writing of a char to the address past current last character. You also need to write null in next position:

int len = strlen(meh);
meh[len] = letter;
meh[len + 1] = '\0';



另外,请检查缓冲区是否足够大以容纳另外一个字符.

与您自己的代码进行比较.没有诸如"\ NUL"这样的字符.此外,您两次计算strlen.为什么?此功能仅检测空字符,您已在之前替换了空字符.它无法工作.

—SA



Also, check if you buffer is big enough to fit one more character.

Compare with your own code. There is not such character as ''\NUL''. Also, you calculate strlen twice. Why? This function simply detect null character, which you replaced one line before. It could not work.

—SA


这篇关于如何将char扩展到字符串的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆