C синтаксический анализатор для добавления / sub / div / mul.Чтение ввода от пользователя хочет завершить мою программу на точку с запятой вместо нажатия Enter - PullRequest
1 голос
/ 10 июля 2019

Я написал программу на C, которая будет читать, используя пользовательский ввод read (), например:

add 1 2 3 Result: 6

Теперь дело в том, что чтение остановит чтение после нажатия клавиши ввода. Что если я хочу прекратить использование любого другого символа, кроме нажатия клавиши ввода? Например:

add 1 2 3; Result: 6

Примечание -> Как я нажимаю; чтение должно прекратить чтение и результат должен отображаться.

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) {
while(1) {
char buff[50];
int rcount = read(STDIN_FILENO, buff, 50); //Reading user input
//write(1, buff, rcount);
buff[rcount - 1] = '\0'; //Converting user input as a string(char array)

/*If nothing is given and user press enter*/
if(strcasecmp(buff, "") == 0) {
    write(1, "Invalid argument\n", sizeof("Invalid argument\n"));
}

/*Getting the first argument*/
char *arr = strtok(buff, " ");

if(strcasecmp(arr, "exit") == 0) {
    break; //Break out of loop when exit is typed in
}
if(strcasecmp(arr, "add") == 0) {
    add(arr); //When first arg is add, call to add func
}
else if(strcasecmp(arr, "sub") == 0) {
    subtract(arr); //When first arg is sub, call to sub func
}
else if(strcasecmp(arr, "mul") == 0) {
    multiply(arr); //When first arg is mul, call to mul func
}
else if(strcasecmp(arr, "div") == 0) {
    divide(arr); //When first arg is div, call to div func
}
/*When first argument is anything else*/
else {
       write(1, "Invalid argument\n", sizeof("Invalid argument\n"));
}

printf("\n");


}
}

void add(char *arr) { //To add numbers --> args > 1

int sum = 0;
while(arr != NULL) { //Loop to get all the numbers and using them to   perform task
    //printf("%s\n", arr);
    int a = atoi(arr); //Converting arg/number to int
    sum += a;
    arr = strtok(NULL, " \n;");
}
char w[50];
int count = sprintf(w, "Result: %d\n", sum); //to use 'write', need to store sum as result so using sprintf instead of printf. Guess we've got no other option? 
write(1, w, count);
return;
}

void subtract(char *arr) { //To subtract numbers --> args > 1

    arr = strtok(NULL, " \n"); //To move to second arg
int subt = (int) atoi(arr); //to get the first number/2nd arg, as we will subtract remaining nums from this

arr = strtok(NULL, " \n"); //To move to remaining numbers, args > 2
    while (arr != NULL) {
    //printf("%s\n", arr);
        int a = atoi(arr);
        subt = subt - a;
        arr = strtok(NULL, " \n");
    }

char w[50];
int count=sprintf(w, "Result: %d\n", subt);
write(1, w, count);
return;
}

void multiply(char *arr) { //To multiply numbers --> args > 1

int mult = 1;
arr = strtok(NULL, " \n");
while (arr != NULL) {
//printf("%s\n", arr);
    int a = atoi(arr);
    mult = mult * a;
    arr = strtok(NULL, " \n");
}
char w[50];
int count=sprintf(w, "Result: %d\n", mult);
write(1, w, count);
return;
}

void divide(char *arr) { //To divide numbers --> args > 1

arr = strtok(NULL, " \n");
float div = (float) atoi(arr);
//printf("%f", div);
//printf("\n");
arr = strtok(NULL, " \n");
    while (arr != NULL) {
    //printf("%s\n", arr);
        float a = (float) atoi(arr);
        div = div / a;
        arr = strtok(NULL, " \n");
    }

char w[50];
int count=sprintf(w, "Result: %f\n", div);
write(1, w, count);
return;
}

Ответы [ 2 ]

0 голосов
/ 11 июля 2019

попробуйте man ncurses для получения дополнительной информации, но это должно работать на большинстве юниксов:

  cc g.c -lncurses
  ./a.out
  cat g.c:  
    #include <ncurses.h>
    void main(void) {
        initscr();
        cbreak();
        while (getch() != ';') {
        }
        nocbreak();
        endwin();
    }
0 голосов
/ 10 июля 2019

Вот пример, который может помочь, вы можете передать любой завершающий символ в него по своему усмотрению:

int add(char *str, char term)
{
    int res = 0;
    while (*str)
    {
        while (*str && !isdigit(*str))
             str++;
        if (*str && isdigit(*str))
             res += atoi(*str);
        if (*str == term)
             break ;
        while (*str && isdigit(*str))
             str++;
    }
    return res;
}
...