Nishalc
Nishalc

Reputation: 33

Scanf in c seems to require double input?

This is probably a really basic question but has me stumped so here goes.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    float argument = 8.86;
    printf("%f%\n", argument);
    argument = 7.75;
    printf("%f%\n", argument);
    scanf("%f%\n", &argument);
    printf("%f%\n", argument);
    return 0;
}

I just wrote this code to help me figure out whats going on. Basically, the scanf seems to require me to put any number then press enter as expected, but then enter another number and press enter or just press enter (after which it will then print the value put the FIRST time time). Shouldn't the code just immediately print the entered number and finish?

Could anyone explain how or why this is happening, thanks!

Upvotes: 2

Views: 993

Answers (4)

S.G
S.G

Reputation: 127

**Only change in scan function **

from scan(%d\n) to

Upvotes: 0

acusp
acusp

Reputation: 11

First, you have an extra % in printf() and scanf() function; Second, you should not have \n in scanf() function; if have the \n, the console will ignore new line, space and all blank characters when you input.

Maybe like this:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    float argument = 8.86;
    printf("%f\n", argument);
    argument = 7.75;
    printf("%f\n", argument);
    scanf("%f", &argument);
    printf("%f\n", argument);
    return 0;
}

I am also a beginner in C language. We come together!

Upvotes: 1

Victor Viola
Victor Viola

Reputation: 585

Try this:

#include <stdio.h>

int main()
{
   char str1[20], str2[30];

   printf("Enter String 1: ");
   scanf("%s", &str1);

   printf("Enter your String 2: ");
   scanf("%s", &str2);

   printf("String 1: %s\n", str1);
   printf("String 2:%s", str2);

   return(0);
}

Upvotes: 0

P.P
P.P

Reputation: 121387

You have an extra % in scanf() and printf() calls. scanf() attempts to intrepret it as additional conversion character. This results in undefined behaviour. Remove them.

If you want to print % sign, use %%.

E.g.:

printf("%f%%\n", argument);

Upvotes: 3

Related Questions