简体   繁体   中英

Input with scanf() on two lines

So, in the terminal, my whole program output in C is supposed to look like this (text between ** is user input)

**Ax Ay alpha**

**Bx By beta**

d Cx Cy

My current code accepts only the first line, the second line is somehow not scanned and it instead tries to give me output already. Here's the input line of code, I think the problem is just in that part.

scanf("%2f %2f %2f", &Ax, &Ay, &alpha );
scanf("%2f %2f %2f", &Bx, &By, &beta );

Whole code

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

#define PI 3.14159265

int main(){
    float alpha, beta, Ax, Ay, Bx, By;
    float d, Cx, Cy;

    scanf("%2f %2f %2f", &Ax, &Ay, &alpha );
    scanf("%2f %2f %2f", &Bx, &By, &beta );

    /* calculaions are here, whole lot of mess */

    printf("%.2f %.2f %.2f \n", d, Cx, Cy );
}

The problem is following: I input the first three variables - the Ax, Ay and alpha. Then, when I press enter, what I want it to do is to let me input the Bx, By and beta too. Instead, it already shows me the results and ends the program.

I suspect it's a locale issue, try checking scanf() return value to see if the input matched the format string

#include <stdio.h>

int main()
{
    float Ax, Ay, Bx, By, alpha, beta;

    if (scanf("%f%f%f", &Ax, &Ay, &alpha) != 3)
    {
        fprintf(stderr, "Invalid input.\n");
        return -1;
    }

    if (scanf("%f%f%f", &Bx, &By, &beta) != 3)
    {
        fprintf(stderr, "Invalid input.\n");
        return -1;
    }
    return 0;
}

that is a clear of example of the kind of problems that appear when you misuse a function, scanf() has a return value for a reason.

Test the code with integer numbers and if it works, switch the decimal separator from '.' to ',' or viceversa.

Also, it could be that you are limiting the input to 2 characters, which is a problem for almost any floating point number, since 1.2 has 3 characters, remove that.

What did you want to achieve with %2f ? That will limit scanning to 2 digits. I think you just want to print two decimal places after zero:

replace "%2f" with "%0.2f" , In other words do this:

float a, b, c, d, e, f;
scanf("%f %f %f", &a, &b, &c);
scanf("%f %f %f", &d, &e, &f);
printf("%0.2f %0.2f %0.2f\n", a+b, d+e, f+c);

and your program will work correctly. The %2f is causing the behavior you described.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM