Home > database >  C anomaly invalid output
C anomaly invalid output

Time:10-09

I have code that needs to run some functions with arguments from stdin. First function counts factorial of argument, second one counts length and square of round with radius presented by argument. Third needs just to printf its arguments.But after my input I have very strange result. My IDE is Xcode

Input:

5
1.3
8
8
fgd

Expected output:

120
Obvod: 8.168134 Obsah: 5.309287
88fgd

Real output:

120
Obvod: 8.168134 Obsah: 5.309287
88
fg

Whats wrong with last input? Thanks a lot in advance for your answer! The whole code below:

#include <stdio.h>
#include <stdlib.h>
int factorial (int value)
{
    int fac = value;
    if (value == 0)
    {
        return 1;
    }
    else if (value < 0)
    {
        return 0;
    }
    for (int i = 1; i < value; i  )
    {
        fac *= value - i;
    }
    return fac;
}
void radius (float rad, float* lep, float* sqp)
{
    const float pi = 3.14159;
    if (rad < 0)
    {
        printf("Obvod: 0 Obsah: 0\n");
    }
    float lenght = 2 * pi * rad;
    float square = pi * (rad * rad);
    *lep = lenght;
    *sqp = square;
    printf("Obvod: %f Obsah: %f\n", lenght, square);
   
}
void read_array_data(int h, int w, char x1, char x2, char x3)
{
    printf("%i%i%c%c%c\n", h, w, x1, x2, x3);
    
}
int main()
{
    char c1;
    char c2;
    char c3;
    int f, height, width;
    float r;
    float radius_container, square_container;
    float* p1 = &radius_container;
    float* p2 = &square_container;
    scanf("%i", &f);
    scanf("%f", &r);
    scanf("%i", &height);
    scanf("%i", &width);
    scanf("%c%c%c", &c1, &c2, &c3);
    printf("%i\n", factorial(f));
    radius(r, p1, p2);
    read_array_data(height, width, c1, c2, c3);
}

CodePudding user response:

scanf(" %c%c%c", &c1, &c2, &c3);
//    ^^^ insert space here

When you hit Enter from the previous scanf, a newline is left in stdin. That newline is read into c1, the f into c2, and finally g into c3. When you print, the newline prints dropping to the next line, followed by fg. The leading space tells scanf to skip that leading whitespace. After that, the fgd characters will be read into c1, c2, c3 as you expect.

Demonstration

See scanf("%c") call seems to be skipped for more info

  • Related