user13468242
user13468242

Reputation:

Why am i not getting the correct output

I am writing a piece of code to ask for two specific points in the format P0 x y. If the user types in Q then the program terminates, for some reason I have trouble outputting the user input (P0 x y) into an output. When I try to run the code and type P0 2 3 it says I have chosen points 0 2.00 3.00.

While the desired output is P0 2 3.

#include <stdio.h>

void main() {
    float a, b;
    char Q, P, input;

    printf("");
    scanf("%c", &input);

    if (input == 'Q') {
        printf("quitting program");
        return (0);
    } else {
        scanf("%c" "%f" "%f", &input, &a, &b);
        printf("you have chose points: %c %f %f", input, a, b);
    }
    return (0);
}

Upvotes: 1

Views: 115

Answers (2)

anatolyg
anatolyg

Reputation: 28300

As the other answer also mentions, when checking for Q in input, the input byte is consumed. The C standard library provides a fix for this specific problem: you can "return" the consumed byte to the input device (keyboard buffer), and later retry reading from input.

The function is ungetc. It requires quite specific syntax (you should "unget" the same value as was just read; also you must use stdin to specify that you are working with keyboard) and only works for one byte, exactly as you need.

Here is your code with my updates and comments.

#include <stdio.h>

int main()
{
    float a, b;
    char Q; // only used for checking the "quit" condition
    char input[10]; // assuming 9 characters + terminating byte is enough

    scanf("%c", &Q);

    if(Q=='Q')
    {
        printf("quitting program");
        return (0);
    }
    else
    {
        ungetc(Q, stdin); // return one byte to the input device
        scanf( "%s" "%f" "%f", input, &a, &b); // "%s" read from the input as string now
        printf("you have chose points: %s %f %f",input, a, b);
    }
    return 0;
}

Upvotes: 1

Hitokiri
Hitokiri

Reputation: 3699

Because you use two scanf. First scanf reads P then second scanf read 0 from command line (from stdin). So after second scanf, input = '0'. This is reason why your program prints 0 2.00 3.00

If you want to print out P0 you have to use string, for example the example below:

#include <stdio.h>

int main()
{
    float a, b;
    char Q, P, input;
    char point[3] = {'\0'};
    scanf( "%c" , &input);
    point[0] = input;

    if(input=='Q')
    {
        printf("quitting program");
        return 0;
    }
    else
    {
        scanf( "%c" "%f" "%f", &input, &a, &b);
        point[1] = input;
        printf("you have chose points: %s %f %f",point, a, b);
    }
    return 0;
}

Upvotes: 1

Related Questions