my getstring function is messing up if it's used after the program accepts an integer value
the program does this :
enter name 1 : mike
enter name 2 : john
enter age 1 : 7
enter name 3 : //after age 1 is entered name 3 is skipped and the program asks for age 2
enter age 2 : 8
Code:
#include <stdio.h>
void getstring(char str[]){
int state = 1;
int x = 0;
char ch;
while( (ch=getchar()) != '\n' )
{
if( ch == ' ' || ch == '\t' )
{
if(state == 0)
{
str[x++]= ch;
state = 1;
}
}
else
{
str[x++]= ch;
state = 0;
}
}
str[x] = '\0';
return ;
}
int main(void){
int x,y;
char name[50];
char name2[50];
char name3[50];
printf("Enter name 1: ");
getstring(name);
printf("Enter name 2: ");
getstring(name2);
printf("\nEnter age 1: ");
scanf("%d",&x);
printf("\nEnter name 3: ");
getstring(name3);
printf("\nEnter age 2: ");
scanf("%d",&y);
getchar();
return 0;
}
positive criticism as well as solutions would be much appreciated
Also, thanks to Whiteflags and Grumpy for helping me with my last error.