I have a simple program which receives input from 3 different functions, 2 return ints, 1 returns a char, but the third function doesn't scanf for some reason it skips that step entirely.
#include <stdio.h>
int get_height();
int get_length();
char get_symbol();
void draw_rectangle(int h, int l, char s);
int main () {
int h, l;
char s;
h = get_height();
l = get_length();
s = get_symbol();
draw_rectangle(h, l, s);
return 0;
}
int get_height() {
int i;
printf ("Please enter the height of the rectangle: ");
scanf ("%d", &i);
return i;
}
int get_length() {
int i;
printf ("Please enter the length of the rectangle: ");
scanf ("%d", &i);
return i;
}
char get_symbol() {
char i;
printf ("Please enter the symbol for the rectangle: ");
scanf ("%c", &i);
return i;
}
void draw_rectangle(int h, int l, char s) {
printf ("%d %d %c", h, l, s);
}
When I run this, i can scan for height and length but it prints the prompt to scan for the char but then skips the user input and prints the value for h and l but no s. What am i missing here?
Previous scanf leaves a newline in the input buffer which is consumed by:
scanf ("%c", &i);
Just change it to:
scanf (" %c", &i);
Notice the space. This will tell scanf to ignore all whitespaces.
You need to consume the newline characters that are being left by the previous scanf() calls. A simple way would be:
scanf ("%d", &i);
getchar();
in each function where it's used. Or with just the one call:
scanf(" %c", &i);
the space will tell it to skip the previous tabs, newlines, or spaces.
stdin is buffered and when the user enters a digit you get a newline char too. The scanf taking the character is therefore picking up one of those left over newlines
You can also use
fflush(stdin);
scanf("%c",&i);
It will resolve your problem. As fflush clears the buffer before reading the character
Related
I have a for loop, which I want to get the input from the user and print the associated ascii value. But it only asks for the user input in the second iteration, which is followed and preceded by the output 10. I tried to get rid of new-line characters, but it still prints out 10.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: \n");
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
Maybe simpler (though using scanf() for user input is not recommended)
scanf(" %c", &character);
// ^ skip otional leading whitespace
Your whole program using fgets() for user input (and my indentation, spacing, style; sorry)
#include <stdio.h> // printf(), fgets()
#include <stdlib.h> // strtol()
int main(void) {
int number;
char buffer[100]; // space enough
printf("Enter the number:");
fgets(buffer, sizeof buffer, stdin);
number = strtol(buffer, 0, 10); // error checking missing
for (; number > 0; number--) {
printf("Give a char: ");
fgets(buffer, sizeof buffer, stdin); // reuse buffer, error checking missing
if (buffer[0] != '\n') {
printf("The associated ascii value of '%c' is %i.\n", *buffer, *buffer);
}
}
return 0;
}
This should solve your problem. getchar() will read the extra newline character from buffer.
#include <stdio.h>
int main(void){
int number;
printf("Enter the number:");
scanf("%i", &number);
for( ; number > 0; number--){
char character;
printf("Give a char: ");
getchar();
scanf("%c", &character);
printf("The associated ascii value is %i \n", character);
}
return 0;
}
regarding;
scanf("%c", &character);
the first time through the loop the '\n' is input.
on all following passes through the loop, the scanf() fails, so the value in character does not change.
This is a prime example of why your code should be error checking.
for instance, to error check the call to scanf():
if( scanf("%c", &character) != 1 )
{
fprintf( stderr, "scanf for a character failed\n" );
break;
}
the 1 is because the scanf() family of functions returns the number of successful: input format conversion specifiers or EOF and it is best to assure the 'positive' status.
Why does my program close before taking the input for k and then displaying it.
I am writing a code for a menu based program so I need to take input from user after he has entered the information so I can have 1.Print names 2.Exit
while doing this I realized my program didn't take the input and just skipped the part where it is supposed to take value of l from user. So trying to debug it I deleted stuff and came down to this simple program and realized it still wont work any idea why?
#include <stdio.h>
struct student
{
char name[50];
char lname[50];
float marks;
} s[15];
int main ()
{
int i, j,k;
printf("Please enter the number of students:\n");
scanf ("%d", &j);
printf ("Please enter the information for students as asked.\n");
for (i = 0; i < j; i++)
{
scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
}
printf("Please enter a number\n");
scanf ("%d", &k);
printf("your number was %d", k);
return 0;
}
scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
should be
scanf ("%s %s %f", s[i].name, s[i].lname, &s[i].marks);
The \n in scanf just consumes newline char. It will continue consuming newline until a non-newline char is found, which is put back into stdin for the next IO operation
Try this Code
#include<stdio.h>
typedef struct student
{
char name[50];
char lname[50];
int mark;
}S;
int main ()
{
int i, j,k;
printf("Please enter the number of students:\n");
scanf ("%d", &j);
S record[j];
for (i = 0; i < j; i++) {
printf ("Please enter the information for %d student as asked.\n",i+1);
scanf ("%s %s %f",record[i].name, record[i].lname, &record[i].mark);
}
printf("Please enter a number\n");
scanf ("%d", &k);
printf("your number was %d \n", k);
return 0;
}
You were declaring structure student array in the structure declaration itself.you have to declare the array in main function.
I'm pretty new to C, and I have a problem with inputing data to the program.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!
Try:
scanf("%d\n", &a);
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
Edit:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...
scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
getchar();
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
return 0;
}
Note:
If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function.
If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
you should do this way.
fgetc(stdin);
scanf("%c",&c);
if(c!='y')
{
break;
}
fgetc(stdin);
to read input from scanf after reading through gets.
scanf("%d", &a); can't read the return, because %d accepts only decimal integer. So you add a \n at the beginning of the next scanf to ignore the last \n inside the buffer.
Then, scanf("\n%s", b); now can reads the string without problem, but scanf stops to read when find a white space. So, change the %s to %[^\n]. It means: "read everthing but \n"
scanf("\n%[^\n]", b);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
scanf("\n%[^\n]", b);
//first \n says to ignore last 'return'
//%[^\n] read until find a 'return'
printf("---------\n");
printf("Name: %s\n\n", b);
system("pause");
return 0;
}
The scanf function removes whitespace automatically before trying to parse things other than characters. %c, %n, %[] are exceptions that do not remove leading whitespace.gets is reading the newline left by previous scanf. Catch the newline usinggetchar();
scanf("%d", &a);
getchar(); // catches the newline character omitted by scanf("%d")
gets(b);
https://wpollock.com/CPlus/PrintfRef.htm
Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
//the change is here*********************
printf("Input your name: ");
gets(b);
gets(b);
//the change is here*********************
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
I tried to execute the following simple code in ubuntu 15.10 But the code behaves odd than expected
#include<stdio.h>
int main(){
int n,i=0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%c",&val);
int count=0;
for(i=0;i<20;i++){
if(a[i]==val){
printf("\n%c found at location %d",val,i);
count++;
}
}
printf("\nTotal occurance of %c is %d",val,count);
return 0;
}
output:
--------------------------
Enter the value : 12345678
Enter the value to be searched :
Total occurance of is 0
The second scanf to get the value to be searched seems not to be working. The rest of the code executes after the first scanf without getting input second time.
After first scanf(), in every scanf(), in formatting part, put a whitespace
So change this
scanf("%c",&val);
into this
scanf(" %c",&val);
Reason is, scanf() returns when it sees a newline, and when first scanf() runs, you type input and hit enter. scanf() consumes your input but not remaining newline, so, following scanf() consumes this remaining newline.
Putting a whitespace in formatting part makes that remaining newline consumed.
You can use fgets():
#include<stdio.h>
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
fgets(a, 20, stdin);
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
or clear stdin:
#include<stdio.h>
void clearstdin(void) {
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');
}
int main() {
int n, i = 0;
char val;
char a[20];
printf("\nEnter the value : ");
scanf("%s",a);
clearstdin();
printf("\nEnter the value to be searched : ");
scanf("%c", &val);
int count = 0;
for (i = 0; i < 20; i++) {
if (a[i] == val) {
printf("\n%c found at location %d", val, i);
count++;
}
}
printf("\nTotal occurance of %c is %d", val, count);
return 0;
}
Also, see C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
printf("\nEnter the value : ");
scanf("%s",a);
printf("\nEnter the value to be searched : ");
scanf("%d",&val); // here is different
i don't know why, but code above working...
scanf("%d",&val);
You can use " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.
For example when I input 2 for num1 and 3 for num2, I expect to get 8 for the output as soon as I enter the second number. However, the program expects me to input one more integer, and I just input a random number like 242 and it still outputs 8, which means that it does not affect the result. So my question is why is there the third input?
Thank you for your help!
#include "stdafx.h"
int Power (int num1, int num2);
int main ()
{
int a, b;
puts ("Enter two numbers, a and b:\n");
scanf ("%i\n", &a);
scanf ("%i\n", &b);
printf ("%i\n", Power(a, b));
return 0;
}
int Power (int num1, int num2)
{
int sum=1;
for (int i=1; i<=num2; i++){
sum= sum*num1;
}
return sum;
}
Get rid of the newlines: \n, in your scanf format strings, or just use a single scanf, e.g.:
scanf("%i%i", &a, &b);
Or:
scanf ("%i", &a);
scanf ("%i", &b);
Your scanf() doesn't need the "\n".
scanf ("%i", &a);
scanf ("%i", &b);
You should remove the '\n' from your format string in your calls to scanf.