字符串显示为奇怪的符号
我在另一项作业中遇到了麻烦,其中我的字符串将 printf 作为无意义的符号,例如菱形中的问号或随机字符。
这次我试图这样做,
char *word = "blah";
printf("word: %s", word);
这给了我一些胡言乱语,甚至与单词的长度不一样。我已经包含了 string.h。
我想做的是获取一个字符串,一次将两个字母附加到字符串的前面或后面,然后从字符串的后半部分提取字符。使用以下方法附加:
int len = strlen(word);
word[len] = 'd';
另外,如何提取最后两个字符?我假设我会通过获取单词的 strlen 并将其转换为字符数组并从索引复制到索引来提取它。有更好的办法吗?另外,随机问题:什么时候使用'\0'?这种情况下需要吗?
非常感谢任何可以帮助我的人。
I have been having trouble with this with another assignment where my strings would printf as nonsensical symbols, like a question mark in a diamond or random characters.
This time I am trying to do
char *word = "blah";
printf("word: %s", word);
This gives me gibberish that isn't even the same length as the word. I have included string.h.
What I am trying to do is take a string, append two letters one at a time to either the front or back of the string, and then extract the characters from the back half of the string. Using the following method to append:
int len = strlen(word);
word[len] = 'd';
Also, how do I extract say the last two characters? I'm assuming I'd extract it by getting the strlen of word and turning it into a character array and copying from indice to indice. Is there a better way? Also, random question: when do I use '\0'? Is it needed in this case?
Much thanks to anyone who can help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码查找
单词
的长度,该数字不在末尾包含空终止符。然后,您继续使用以下行覆盖终止符:因此,现在您的字符串无法正确终止,并且无法与 I/O 函数很好地配合。记住;因数从零开始。长度为
x
的字符串具有0
到x-1
范围内的可访问字符。除此之外,您没有向我们展示您如何创建
word
,因此那里也可能存在问题。如果您一开始就没有正确初始化它,那么您可能只是踩踏了不应该修改的内存。编辑:好的,所以您已经发布了创建字符串的代码,这是另一个问题:
这实际上应该是
因为
word
指向只读内存。您不得修改word
指向的内容。相反,如果稍后需要修改字符串,请创建一个数组:Your code finds the length of
word
, a number which does not include the null terminator at the end. You then proceed to overwrite the terminator with the following line:So now you have a string which does not terminate properly and won't play nicely with I/O functions. Remember; indeces start at zero. A string of length
x
has accessible characters in the range of0
throughx-1
.Aside from that, you don't show us how you created
word
in the first place, so there may be a problem there as well. If you didn't initialize it properly to begin with you're probably just stomping all over memory that you shouldn't be modifying.EDIT: Ok, so you have posted the code where you create the string, and here is another problem:
That should really be
because
word
points to read only memory. You are not allowed to modify whatword
points to. Instead, create an array if you need to modify the string later on:这里的 word 是一个指向字符的指针,因此它的 malloc 一次是固定的。因此,您想要对此字符串进行任何更改,您必须使用 memcpy 函数或 strcpy,strcat 函数。
使用这些函数,您可以在字符串之前或之后附加任意数量的字符
Here word is a pointer to character so its malloc is fix at a time. so you want to any change in this string you have to use
memcpy
functions orstrcpy,strcat
functions.Using these functions you can append any number of characters before or after the string