Scanf is being ignored [duplicate] - c

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 7 years ago.
#include <stdio.h>
#define length 20
main()
{
float x;
int y;
float array1[length], array2[length], array3[length];
float ray[length];
int size1 = insert(array1, length);
printf("enter number: ");
scanf("%d", &y);
int size2 = insert(array2, length);
int size3 = insert(array3, length);
}
int insert(float a[], int size)
{
int n = 0;
while(n<size && scanf("%f\n", &a[n]) == 1)
{
printf("you entered: ");
printf("%2.1f\n", a[n]);
n++;
}
return n;
}
When I run the program, it executes the first insert okay, but the next time function is called, scanf() seems to be ignored completely. I tried putting it right after where insert is done, but that's ignored as well.

Use %*c in scanf to consume the newlines along with space around %d in the scanf in main(). I tested the below code on MingW and it seem to work. The '\n' in your scanf is being consumed making it scanf() return while the '\n' at the press of enter key still remains in IO buffer to be consumed by scanf() again; hence the weird behaviour.
#include <stdio.h>
#include <stdlib.h>
#define length 20
int insert(float *a, int size)
{
int n = 0;
while(n<size && scanf("%f%*c", &a[n]))
{
printf("you entered: ");
printf("%2.1f\n", a[n]);
n++;
}
return n;
}
int main(int argc, char* argv[])
{
float x;
int y;
float array1[length], array2[length], array3[length];
float ray[length];
int size1 = insert(array1, length);
printf("enter number: ");
scanf("%d", &y);
int size2 = insert(array2, length);
int size3 = insert(array3, length);
return 0;
}

In the scanf format string, change "%f\n" to "%f". The \n in a scanf format string does not mean "wait for newline".
You do not need to worry about waiting for newline, because the only format specifiers you use are %f and %d, which both discard any leading whitespace.

Related

Why does my program exit after taking an input?

Consider:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter %d values\n", n);
for(int i=0; i<n; i++)
{
scanf("%[^\n]s", &name);
}
}
Whenever I am entering the value of n, it just prints (Enter n values) and exits the program. The for loop never runs. It ran successfully for the first time, but after that it just exits the program.
There were some answers that said it will not print anything. I don’t want it to print just to take input n times. It is not doing that.
My aim is to take n as input and then take strings of names (like harry, robin, etc.) n number of times as input.
Your code is a little incomplete. And there are a few errors here: scanf ("%[^\n]s", &name)
Do this and everything will be fine:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf(" %d", &n);
printf("Enter %d values\n", n);
for(int i=0; i<n; i++)
{
scanf(" %99[^\n]", name);
printf("%s\n", name);
}
return 0;
}
scanf is particularly unsuited for user input.
You probably want this:
int main() {
int n;
char name[100];
int number;
printf("Enter the value of n\n");
scanf("%d", &n);
printf("Enter %d values\n", n);
for (int i = 0; i < n; i++)
{
// the space at the beginning of "%[^\n]"
// gets rid of the \n which stays in the input buffer
scanf(" %[^\n]", name); // also there sis no 's' at the end of the "%[^\n]" specifier
printf("name = %s\n", name); // for testing purposes
}
}
But this doesn't actually make much sense because the program is asking for n names, but at each run of the for loop the previous name will be overwritten with the new name.
Also be aware that scanf("%[^\n]", name); is problematic because if the user types more than 99 characters you'll get a buffer overflow.

Why scanf is not working in functions using C programming? [duplicate]

This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 1 year ago.
I wrote this C program using 2 functions, but in this first case grade() is not prompting for the input:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Function Type 2\n");
x = motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y = grade();
printf("\nReturned value is %c\n", y);
}
int motivQuote()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n == 1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n == 2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n + 2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade, 1);
return grade;
}
And here in the second case, grade() prompts for the input only in the second call, but the first one is not working:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Functions\n");
x= motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y= grade();
printf("\nSubject2: ");
z= grade();
printf("Returned values are %c and %c\n", y, z);
}
int motivQuote ()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n==1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n==2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n+2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade,1);
return grade;
}
Can anyone tell me what's the reason please?
Use scanf(" %c",&grade,1); with a space before %c. This will solve the problem.

Loop Gone wrong [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
I'm pretty new in C.
My problem is the code keep looping at that line ( you can check the code) while what i wanted is for it to loop the whole for statement, not a single line.
English is not my first language so i'm truly sorry
#include <stdio.h>
int hw;
int uts;
int uas;
float hasil_uts;
float hasil_uas;
float hasil_hw;
char opsi;
int main (void) {
int n1; //Homework
int c1;
for (c1=0;opsi != 'n';c1++) {
printf ("Input : ");
scanf ("%d",&hw);
n1 += 1;
hasil_hw += hw;
printf ("\nInput another marks? (y/n)"); // it loops here when it run
scanf ("%c",&opsi);
}
return 0;
}
you have to add one space in scanf like this scanf (" %c",&opsi); ,otherwise you will take \n as your character in scanf.
also note that you are using uninitialized variable n1 and hasil_hw. you have to add n1=0 and hasil_hw=0 to your code.
also as mentioned in comments you should check scanf returned value.
look
int hw;
int uts;
int uas;
float hasil_uts;
float hasil_uas;
float hasil_hw=0;
char opsi;
int main(void) {
int n1=0; //Homework
int c1;
for (c1 = 0; opsi != 'n'; c1++) {
printf("Input : ");
if ( scanf("%d", &hw) != 1)
{
fputs ("error: invalid value.\n", stderr);
return 1;
}
n1 += 1;
hasil_hw += hw;
printf("\nInput another marks? (y/n)"); // it loops here when it run
if (scanf(" %c", &opsi) != 1)//add space before %c
{
fputs ("error: invalid value.\n", stderr);
return 1;
}
}
return 0;
}

How to make code say 'invalid input' when a user enters a character or a string (Validate)

I'm new to c and i just wanted to know how to make my code say ' invalid input' if they decide to enter a character or gibberish.
My code is just a simple Celsius to Kelvin (i know very simple) and i just adds 273 to any inputted number. i tried to use isdidgit but it was unsuccessful.
My code;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int temp = 273;
int cel;
int cel2;
int choice;
switch (choice)
{
case 1:
printf("enter ce to conv to kel: ");
scanf("%ld", &cel);
cel2 = cel + temp;
printf("%d in Celsuis is: %d Kelvin \n", cel, cel2)
I accept all feedback / improvements,
thanks
~Neamus
Presently, your code has no way to recover from an invalid input. That is, if a user enters "a" when prompted, scanf() will never return because it will be waiting for a base-10 integer value.
What you will need to do is read the input as a C-string and process that:
char input[80];
do {
printf("enter ce to conv to kel: ");
scanf("%79[^\n]\n", input); // read until newline; toss newline
} while (input_is_bad(input)); // your function to validate input
cel = atoi(input); // atoi parses C-string, returning an int
cel2 = cel + temp;
printf("%d in Celsuis is: %d Kelvin \n", cel, cel2);
Inside your own input_is_bad() function, you can print a message stating that the input is not valid.
You can achieve this by using fgets and strtol. See the following code:
#include<stdio.h>
#include <stdlib.h>
int main()
{
int temp = 273;
int cel;
int cel2;
int choice;
int flag;
char *p, str[100];
printf("enter ce to conv to kel: ");
while (fgets(str, sizeof(str), stdin)) {
cel = strtol(str, &p, 10); //number of base 10
if (p == str || *p != '\n') {
printf("Please enter an integer: ");
}
else break; //if input is integer then break the loop
}
//do your calculations here
return 0;
}

Why do I get a segmentation error here in my code? [duplicate]

This question already has answers here:
Why does scanf() need & operator (address-of) in some cases, and not others? [duplicate]
(5 answers)
Ampersand(&) and scanf in C?
(5 answers)
errors and warning message when using pointer
(3 answers)
Closed 5 years ago.
It's an extremely simple code, when I run it, it lets me enter the int, but when I enter it, the program crashes. I tried putting a printf right after the scanf to check if the program reads the int correctly, it seems it doesn't. I can't output the integer that I input.
#include <stdio.h>
#include <math.h>
void coolfunction(int x, int *y)
{
*y = exp(x);
}
int main()
{
int n;
double result = 0;
printf("Enter an integer: ");
scanf("%d", n);
coolfunction(n, &result);
printf("\n e^%d = %lf \n", n, result);
return 0;
}
Here's a version using a double parameter:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void coolfunction(int x, double *y)
{
*y = exp(x);
}
int main()
{
int n = 0, scanned = 0;
double result = 0;
printf("Enter an integer: ");
scanned = scanf("%d", &n);
if (scanned < 1) {
fprintf(stderr, "value entered not a valid integer\n");
exit(EXIT_FAILURE);
}
coolfunction(n, &result);
printf("\n e^%d = %g \n", n, result);
return 0;
}
You also missed the & in your scanf call: the function needs to know the address of your variable, not its value.

Resources