字符数组后,性格怪异 [英] Strange character after an array of characters

查看:111
本文介绍了字符数组后,性格怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个真正的初学者到C,但我学习!

I am a real beginner to C, but I am learning!

我已经在这个问题之前绊倒,并决定要求它的原因是什么。并请说明您的答案,所以我可以学习的。

I've stumbled upon this problem before and decided to ask what the reason for it is. And please explain your answers so I can learn.

我做了一个程序,它允许你输入5个字符,然后告诉你写的字也回复他们,例如:asdfg - gfdsa。
奇怪的是,一个奇怪的字符被输入的原字后显示。

I have made a program which allows you to input 5 characters and then show the characters you wrote and also revert them, example: "asdfg" - "gfdsa". The weird thing is that a weird character is shown after the original characters that was inputted.

下面是code:

char str[5];
char outcome[] = "OOOOO";
int i;
int u;

printf("Enter five characters\n");

scanf("%s", str);

for(i = 4, u = 0; i >=0; u++, i--){
    outcome[i] = str[u];
}

printf("\nYou wrote: %s. The outcome is: %s.", str , outcome);


return 0;

如果我输入:asdfg它显示:asdfg♣,这是为什么

If I enter: "asdfg" it shows: "asdfg♣", why is that?

感谢您的时间和请说明您的答案:)

Thank you for your time and please explain your answers :)

推荐答案

由于没有空终止符。在C字符串是连续字节(字符)序列与定点字符到底叫空终止('\\ 0')。您code获取用户输入并填充所有5个字符,所以没有结束到您的字符串。然后,当你打印字符串将打印5个字符(asdfg),它会继续打印任何垃圾是在堆栈上,直到遇到一个空终止符。

Because there's no null terminator. In C a "string" is a sequence of continuous bytes (chars) that end with a sentinel character called a null terminator ('\0'). Your code takes the input from the user and fills all 5 characters, so there's no "end" to your string. Then when you print the string it will print your 5 characters ("asdfg") and it will continue to print whatever garbage is on the stack until it hits a null terminator.

char str[6] = {'\0'}; //5 + 1 for '\0', initialize it to an empty string
...
printf("Enter five characters\n");
scanf("%5s", str);  // limit the input to 5 characters

有关限制格式specificer的好处是,即使输入大于5个字符长,只有5将被存储到您的字符串,总​​是留有余地的空终止符。

The nice thing about the limit format specificer is that even if the input is longer than 5 characters, only 5 will be stored into your string, always leaving room for that null terminator.

这篇关于字符数组后,性格怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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