Hello there!
I have been strolling about the threads, looking for similar problems, but haven't found an exact solution... everyone keeps telling, that fgets() should be used for getting user input, instead fof gets(). Cool, let's give it a try. This sample program I copied from a website works just fine:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[80];
int i;
printf("Enter a string: ");
fgets(str, 10, stdin);
/* remove newline, if present */
i = strlen(str)-1;
if( str[ i ] == '\n')
str[i] = '\0';
printf("This is your string: %s", str);
return 0;
}
Yet, my own program is not willing to take any user input...it finishes, before I'd have a chance to type anything!
Code:
#include <stdio.h>
int main(){
/*********************************************************************/
char letter;
printf("Gimme a letter!");
scanf("%c",&letter);
int num;
if(letter=='a'||letter=='b'||letter=='c')
num=2;
else if(letter=='d'||letter=='e'||letter=='f')
num=3;
else if(letter=='g'||letter=='h'||letter=='i')
num=4;
else if(letter=='j'||letter=='k'||letter=='l')
num=5;
else if(letter=='m'||letter=='n'||letter=='o')
num=6;
else if(letter=='p'||letter=='q'||letter=='r'||letter=='s')
num=7;
else if(letter=='t'||letter=='u'||letter=='v')
num=8;
else if(letter=='w'||letter=='x'||letter=='y'||letter=='z')
num=9;
else
printf("Why have not given me a letter?!\n");
printf("The letter is now encoded: %d\n",num);
/**********************************************************************/
printf("Gimme a word of 15 chars!");
char word[15];
fgets(word,16,stdin);
printf("%s",word);
}
I've noticed, that if I comment out the first block and only the second block is left (starting after the second comment line) then fgets() function properly... waits for input and printf() gives back the string. Could anyone explain this to me?