I try to input a number, put the program has an error and crashes.Code:scanf("%d",i); switch(i) { case 1: text2code(); break; case 2: code2text(); break; default: printf("Not a valid input"); break; }
This is a discussion on What's wrong??? within the C Programming forums, part of the General Programming Boards category; Code: scanf("%d",i); switch(i) { case 1: text2code(); break; case 2: code2text(); break; default: printf("Not a valid input"); break; } I ...
I try to input a number, put the program has an error and crashes.Code:scanf("%d",i); switch(i) { case 1: text2code(); break; case 2: code2text(); break; default: printf("Not a valid input"); break; }
I'm assuming i is an integer and as such scanf should be:
Code:scanf("%d", &i);
new problem
I say to get a char, put the program skips that and automatically exits! I've checked this many times, and can't find an error.Code:int i; system("cls"); printf("What Code?\n\nA. Sphere Code\nB. New Code\n: "); i = getc(stdin);
My book uses intergers to store single characters, and getc() or getchar() to get them.
Example, this works:
Code:int i; system("cls"); printf("CODE CRYPTATION\nBy Samuel Fredrickson\n\n"); printf("A. Text -> Code\nB. Code -> Text\n\n: "); i = getchar();
Mixxing scanf and getchar can have undesirable results. Look into using fgets instead of scanf
even this doesn't work!
It's like, for some reason, it's skipping ALL input functions! Why???Code:void text2code() { char i; char *ptr_i = &i; system("cls"); printf("What Code?\n\nA. Sphere Code\nB. New Code\n: "); fgets(ptr_i,1,stdin); /* if(i == 'a') { text2sphere(); } else if(i == 'b') { text2new(); }*/ printf("At End"); return; }
Read the man page for fgets. It will get size - 1 and append a null character to the end. So in that case you are getting 0 bytes from the input.Code:fgets(ptr_i,1,stdin);
Probably because you've got stuff left over in your input stream. Next, don't read single characters with fgets. It defets the purpose of fgets. Fgets is used to read strings, which are null terminated. Thus, you need at least 2 characters (ie: an array), not one.Originally posted by kinghajj
even this doesn't work!
It's like, for some reason, it's skipping ALL input functions! Why???Code:void text2code() { char i; char *ptr_i = &i; system("cls"); printf("What Code?\n\nA. Sphere Code\nB. New Code\n: "); fgets(ptr_i,1,stdin);
Clear stdin first.
while( fgetc(stdin) != '\n' );
Quzah.
Hope is the first step on the road to disappointment.