注意到奇怪的行为与C字符串 [英] Noticing strange behavior with strings in c

查看:124
本文介绍了注意到奇怪的行为与C字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习模式下的静止,可能是以下问题是一个非常愚蠢的,但我没有任何想法,为什么它正在发生。

Still in learning mode and may be the following question is a really dumb but I dont have any idea why it is happening..

#include<stdio.h>
int main()
    {
      /* code to accept string and then a character from stdin */
         char str[20], inp;
         /*take string from stdin */
         printf("string:\n");
         scanf("%s",str);
         fflush(stdin);
         /*input a character */
         printf("char:\n");
         scanf("%c",&inp);/* code does not reach this point and exits */

    }

由于在评论中提及,在我输入字符串,例如。 strng'的code印花字符后仅退出:但它不会等我输入的字符。按我的理解,我给数组足够大的存储字符串,如果输入的字符串比海峡数组的大小更小,编译器会自动在字符串末尾添加空字符,并进一步进行规模。我缺少的东西还是有我的code是错误的。请建议。

As mentioned in the comment, after I input the string , for eg. 'strng' the code just exits after printing char: but it does not wait for me input the character. As per my understanding, I have given the size of the array large enough to store the string and if the string entered is smaller than the size of the str array, the compiler will automatically add null character at the end of the string and proceed further. Am I missing something or is there a mistake in my code. Please suggest.

感谢。

推荐答案

在第二scanf函数像这样在%C 将一个空间:

Put a space before the %c in the second scanf like this:

scanf函数(%C,&安培; INP)

和为他人说 fflush 是输出流只定义了。

And as stated by others fflush is defined only for output streams.

这篇关于注意到奇怪的行为与C字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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