Sorry because I can't think of any better title I have a problem dealing with the input Here is my test code which get the input into a string array then print it on screen again, quite simple
The 1st test code work fine as expected
#include <stdio.h>
int main()
{
int i, index;
char d, c[20];
scanf("%d", index);
for(i=0; i<index; i++){
*(c+i) = getchar();
if (*(c+i)=='$')
break;
}
printf("the string is %s", c);
return 0;
}
the 2nd test code, I did use pointer but c[i] instead and the program didn't run. It's quite strange since *(c+i) and c[i] is equivalent
I changed
*(c+i) = getchar(); // (0)
if (*(c+i)=='$')
to
c[i] = getchar(); // (1)
if (c[i]=='$')
or
c[i] = getchar(); // (2)
if (*(c+i)=='$')
or
*(c+1) = getchar(); // (3)
if (c[i]=='$')
the (3) work fine, no problem happened but in (1) and (2), the output is just the first character of the input regardless how long the string input
Ex: type asdads$
output: a
So the problem lie in the getchar() code there is a different between using pointer and direct element of array to get the input but I don't know what is the problem here
I'll call this problem is "A" because I encounter several problem as I tried different kind of code with scanf and getchar
Now I change the getchar() in each case into scanf
(0)(1)(2)(3): problem A happen. Now none of them work fine with scanf. With getchar, at least (0) and (3) work.
Now, instead of input data directly into c, I input data into d and pass that value of d to c[i]
Usind d = getchar(), problem A happen to all 4 case. scanf give the same result
What is strange is when I hit enter, the program auto break and output is print to screen
That is just a test but here is the current problem I'm dealing with
int z;
printf("continue? [1=yes/0=no] ");
scanf("%d", &z);
switch (z){
case 1: printf("next info is: ");
scanf("%d", &x);
break;
case 0: *end = '\0';
break;
}
This work fine, using scanf with %d is ok, it wait for me to hit 1 or 0 to continue the process. However the problem happened with these 2 code which are expected to perform the same. They don't wait me to hit y/n but go directly to the end
char z;
printf("continue? [y/n] ");
z=getchar(); // using getchar
if(z=='y'){
printf("next info is: ");
scanf("%d", &x);
}
else{
*end = '\0';
}
and
char z;
printf("continue? [y/n] ");
z=getchar();
switch(z=='y'){
case 1: printf("next info is: ");
scanf("%d", &x);
break;
case 0: *end = '\0';
break;
}
So I don't know what is wrong with the code I use and why using pointer to get data is different from using array directly.