Scanf causes C program to crash - c

This simple issue is causing my entire program to crash during the first input. If I remove the input, the program works fine but once I add scanf into the code and enter the input the program crashes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXEMPS 3
// stub program code
int main (void){
char answer;
do
{
printf("\n Do you have another(Y/N): ");
scanf("%c", answer);
}while(answer == 'Y' || answer == 'y');
getchar();
printf(" Press any key ... ");
return 0;
} // main

You must pass the address of the variable to scanf:
scanf("%c", &answer);

Use "&answer". And get rid of the extraneous "fflush()" commands...
Better, substitute "answer = getchar ()".

Related

C: Hi, my code doesn't display the error message properly [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 months ago.
I wrote a code to create a glossary of the most basic C instructions, their function and some definition (explained in a very simplistic way).
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
char dv = '"';
char choice;
int lsel;
printf("%s", "C GLOSSARY\nInstructions' syntax list, their function and definitions\n\n----------------------------------------------\n");
printf("%s", "\nType:\n- 'L' to display the list of instructions currently \n covered in this glossary.");
printf("%s", "\n- 'E' to exit the program\n");
do
{
scanf("%c", &choice);
choice = toupper(choice);
if(choice != 'L')
printf("ERROR: invalid option. Please, try again: ");
} while(choice != 'L');
if(choice == 'E')
return 0; //the code continues...
}
It works, but the message ERROR: invalid option. Please, try again: is displayed two times! Do you know why? If you want to try the code: https://github.com/AndreMarinelli/C-glossary
Thank you :)
Change scanf("%c", &choice); to scanf(" %c", &choice);.
The space in the format specifier allows scanf() to consume any amount of leading whitespace in the input.

Prompt for input and print a response with only one printf()?

C-code only: Ask user if they are married or not. User must input 0 for false. User must input any other character for true. Do it using only one printf.
Ok, so I always turn to stackoverflow as a last resort, because I am trying to figure it out. This, is what I came up with but I get errors and I have done other things like take out scanf("%f", &t), because that is essentially unnecessary. I also made char married[3]; char married[] ="; instead but that doesn't work.
Here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char married[3];
unsigned long t;
int f;
scanf("%f", &t);
scanf("%d", &f);
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married? %s", married);
if (f == 0)
{
married == "no";
}
else
married == "yes";
return 0;
}
Thanks the help is appreciated. Please go easy on me just learning...
I'm not sure you are interpreting the question correctly. It says to print whether the person is married or not. So that's the expected output. It suggests you can do that with one printf. It does not mean the whole program only has one printf so you are allowed to have another printf for the user prompt. It just means avoid using two printfs for the output (one for YES and another for NO). One way to do this is to use the ? operator.
For example:
#include <stdio.h>
#include <string.h>
int main(void)
{
int married = 1;
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?");
scanf("%d", &married);
printf("You %s married\n", married ? "ARE" : "ARE NOT");
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char married[4]; //Space for 'yes' + the NUL-terminator
//unsigned long t; Why do you have this?
int f = 1; //Initialize variables
//scanf("%f", &t); ??
//scanf("%d", &f); Wrong place
printf(" For the following question: Enter 0 if false. Enter anything but 0 if true. Are you married?"); //Remove %s and the argument. You are trying to print an uninitialized array
scanf("%d", &f); //scan input after printing
if (f == 0)
strcpy(married, "no");
else
strcpy(married, "yes"); //Copy strings using strcpy function
return 0;
}

How to fix the running of my program in terms of conditional statements and output in C?

I have a problem with my input for my program:
#include <stdio.h>
#include <stdlib.h>
int confirm()
{
char c;
printf("Confirm (y/n): ");
scanf("%c", &c);
while (scanf("%c", &c))
{
if (c == 'Y' || c == 'y' || c == 'N' || c == 'n')
{
printf("\nThank you. \n");
break;
}
else
{
printf("\nInput not recognised, ry again. \n");
printf("Confirm (y/n): ");
}
}
}
int main(int argc, char* argv[])
{
confirm();
return 0;
}
When it executes, it asks the first question and inputting the answer is fine. However after entering the character (either y or n) the program prints the second question and stops. The whole program is not running. I don't know what I'm doing wrong.
Loose the first scanf at line 9 and (for me) it then seem to work correctly: if ynYN is entered then the confirm function exits, otherwise it continues looping

how to read a char value in C without going to next line

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
(WHY IS MY OUTPUT for the second printf and scanf not waiting for me to input a char before exiting the program?.....what i mean is u know where it says q=getchar();??? shouldnt it wait for to input a char before exiting the program? but for some reason the program just exits when it goes to the next line...
when pressing enter,a character '\n' is inputing.So your getchar() was used before you enter the second character.I think you want the code below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char p,q;
printf("Hello enter char: ");
p=getchar();
printf("the char is: %c\n",p);
int c;
while((c = getchar()) != '\n' && c != EOF && c != ' ') ;
printf("Hello enter char: ");
q=getchar();
printf("the char is: %c\n",q);
return 0;
}
You can also use a getch() instead of getchar() to avoid pressing enter key.
#include <stdio.h>
#include <conio.h>
int main(void)
{
char p,q;
printf("Hello enter char: ");
p=getch();
printf("the char is: %c\n",p);
printf("Hello enter char: ");
q=getch();
printf("the char is: %c\n",q);
return 0;
}
When encountering invalid user inputs, use getchar() to read char, and other similar instances where there are undesired characters stuck at input stream(like in your case it was a newline) I define a constant named FLUSH
#define FLUSH while(getchar() != '\n')
to solve the problem. What this statement does is that it reads a character and then throws it away. Now if you try to place it after one of your getchars i.e.
p=getchar();
printf("the char is: %c\n",p);
FLUSH;
it will read the newline then stops because the condition within the while statement no longer holds.
Note: Using getchar() for prompts leaves a '\n' in the input stream you will find this troublesome once you make another prompt and have not eradicated that '\n'.

scanf gets skipped, even with safeties (getchar())

I know this question gets asked a hundred times over, and I've scoured all of the possibilities, but I guess I'm not adept enough to know where this problem lies. I'm programming a program where I need to fill a struct with data (ints and strings). The first time I tried it it skipped over everything but the first one, but I didn't panic since I remembered from class I needed to use fflush(stdin) to overcome this. Websites I've searched vote against use of fflush(stdin), since it has undefined behaviour. They say using getchar() would eat the extra newline, thus fixing the problem. Hence my code:
int manNode(){
Item *p;
int helper;
p = (Item*)malloc(sizeof(Item));
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
scanf("%u",&helper); //selecting an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
getchar(); //I've just put getchars everywhere for safety.
p->entrytype = helper-1;
helper = 0;
printf("Vul een naam in:\n");
scanf("%s", p->name); //this one fills in fine
getchar();
printf("Vul een vaknaam in: \n");
scanf("%s", p->course); //this one gets skipped if I type more than one letter in the last scanf()
getchar();
printf("Vul een starttijd in:\n"); //From here on out everything gets skipped
p->start = getTijd();
checkTijd(p->start);
printf("Vul een eindtijd in: \n");
p->end = getTijd();
checkTijd(p->end);
I know it's a bit messy, but focus on the scanfs and getchars. getTijd() also has a couple of scanfs in it that scan for integers, they also get skipped. I don't know where to go from here. (The code isn't incomplete, the rest is just irrelevant)
you can define a new getchar
#include <stdlib.h>
#include <stdio.h>
#define getchar(x) (scanf("%c", x))
int main ()
{
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
return 0;
}
update: this may be a better approach
#include <stdlib.h>
#include <stdio.h>
void work_to_do()
{
#define getchar(x) (scanf("%c", x))
char x, y[10];
getchar(&x);
scanf("%s", y);
printf("got %s\n", y);
#undef getchar
}
int main ()
{
work_to_do();
return 0;
}
to solve the scanf newline ignorance and getchar (but still scanf ignores whitespace)
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#define __getchar() (read(2, NULL, 1)) // 2 stands for standard error, we can make the user enter a character.
void work_to_do()
{
char y[10];
__getchar();
scanf("%s", y);
printf("got %s\n", y);
__getchar();
}
int main ()
{
work_to_do();
return 0;
}
and it's good to take a look at this:
Read space-separated values from file
scanf works as documented. Also, there is nothing wrong with scanf so long as its function is understood.
I created a copy of your code and distilled it to highlight what you want to do. You will need to fill-in the rest yourself.
In this code you need to enter a digit and press enter. Then enter a string and press enter, etc. Note. the fflush(stdout) statement is part of the standard C implementation per K&R. The fflush forces the contents of the buffer out to the console. This flushing makes for a reasonable user/computer dialog.
#include <stdio.h>
main()
{
char string[100];
int helper;
printf("Welk type? (Taak:1, Examen:2, Voordracht:3)\n");
fflush(stdout);
scanf("%d",&helper); //select an itemtype
if (helper < 1 || helper > 3)
{
printf("wrong value, please try again");
return 0;
}
printf("Vul een naam in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een vaknaam in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een starttijd in:\n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
printf("Vul een eindtijd in: \n");
fflush(stdout);
scanf("%s", &string[0]);
printf("\n%s\n", string);
}
This code ran on Eclipse with a Microsoft C Compiler.
Also, let me emphasize that if you enter: 1 AAA BBB CCC DDD and press enter then scanf will get executed five times. In this example, the code would run to completion!
So you need to trace your code logic (in this case a straight line) to see how the scanfs are invoked based on what data is entered.
Hope this helps. Please ask if more questions.

Resources