我正在尝试根据子函数的退出值从main函数打印

时间:2014-11-01 23:08:42

标签: c scanf

我想打印从算术计算生成的不同打印语句以及3种不同的错误(错误的格式,除以零和错误的运算符)。

我现在处理的问题是,无论输入是什么,程序都会打印出错误的声明"从退出(50)即使格式正确...

这是我的代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int childFunction(char *string);

char input;
char *string = &input;
int status;
int pid;

int main (void)
{
    printf("This program makes simple arithmetics\n");

    while(1)
    {
        printf("Enter an arithmetic statement, e.g., 34 + 132\n");
        input = scanf("%s",&input);

        pid = fork();

        if (pid == -1)   // Error creating child process
        {
            perror("Impossible to fork\n");
            exit(0);
        }

        else if (pid == 0)    // Child process
            childFunction(&input);

        else
        {
            if (pid > 0)  // Parent process
            {
                printf("Created a child to make your operation, waiting\n");
                wait(&status);

                sleep(2);

                if (WEXITSTATUS(status) == 50)
                printf("Wrong Statement\n\n");

                else if (WEXITSTATUS(status) == 100)
                printf("Division by zero\n\n");

                else
                if (WEXITSTATUS(status) == 200)
                    printf("Wrong operator\n\n");
            }
        }
    }

    return (0);
}

int childFunction(char *string)
{
    int n1, n2;
    char op;
    float div = n1/n2;

    printf("I am a child working for my parent\n\n");
    sscanf(string, "%d %c %d", &n1, &op, &n2);

    if ((sscanf(&input,"%d %c %d", &n1, &op, &n2)) != 3)
        exit(50);

    if (op == '/' && n2 == 0)
        exit(100);

    switch (op)
    {
            case '+':
            printf("\n%d %c %d = %d", n1, op, n2, n1+n2);

            case '-':
            printf("\n%d %c %d = %d", n1, op, n2, n1-n2);

            case '/':
            printf("\n%d %c %d = %f", n1, op, n2, div);

            case '*':
            printf("\n%d %c %d = %d", n1, op, n2, n1*n2);

            default:
            exit(200);
    }
    exit(0);
    sleep(1);
}

1 个答案:

答案 0 :(得分:0)

char input;

if ((sscanf(&input,"%d %c %d", &n1, &op, &n2)) != 3)
    exit(50);

sscanf的第一个参数需要指向字符串的指针,而不是单个字符。