the input buffer in getchar() and scanf

↘锁芯ラ 提交于 2019-12-08 23:09:44

Yes! first of all scanf("%d",&index); must be used you have used it wrong way. You have to pass the address of the variable.

Secondly, in the input buffer the '\n' pressed after a given input is there. You have to put a dummy getchar over here that will consume any extra '\n'.

scanf("%d", index);
getchar();
    for(i=0; i<index; i++){
        *(c+i) = getchar();
        if (*(c+i)=='$')
            break;
    }

Now in the second case(where you use a int as input) it works as '\n'(or any white space) is character is ignored by the scanf (the format specifiee is "%d" not "%c").

#include <stdio.h>
int main()
{
    int i, index;
    char d, c[20];
    scanf("%d",index);//*2
    for(i=0; i<index; i++){
    c[i] = getchar(); // (1)
    if (c[i]=='$')
        break;
}
printf("%d",index); //*1
printf("the string is %s", c);
return 0;
}

If you printf the no. of index(*1) you will know when some situation index = 1. The only space is for NULL in the string.So, There are some problem of your program and it isn't the problem of (1)(2)(3).

You might change the program:

*2 to scanf("%d",&index);

After then, you will complie (1)(2)(3) sucessfully.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!