S
S
samsungovetch2018-07-12 15:55:49
C++ / C#
samsungovetch, 2018-07-12 15:55:49

C - How to process a string entered from the keyboard character by character?

Given symbols s1,s2,... It is known that the symbol s1 is not a space and that there is at least one space among s2,s3,.... Considered are s1,...,sn - characters preceding the first space (n is not known in advance). Convert the sequence s1,..., sn: by removing from each group of consecutive digits in which there are more than two digits and preceded by a dot, all digits starting from the third (for example, ab+0.1973-1.1 is converted to ab+0.19-1.1) ;

#include <string.h>     // strcat
#include <stdio.h>      // printf
#include <ctype.h>      // isdigit

//270Ã
char* get_string(char* str, int a);

int main()
{
    int l;
    char str[256];
    fgets(str, sizeof str, stdin);
    char* res = get_string(str, strlen(str));
    if (res)
    {
        printf("res=%s", res);
        free(res);
    }
    else
    {
        printf("Error. Spacebar can't be first digit.");
    }
    return 0;
}

char* get_string(char* str, int a)
{
    if (str[0] == ' ') //
    {
        return NULL;
    }

    int i = 0, count = 0, bool = 0;
    unsigned index = 0;
    char* result = malloc(a); //


    for (int i=0; i <= a; i++)
    {
        if (i!=0 && str[i] == ' ')
            break;
        else if (str[i] == '.')
            {
                bool = 1;
                result[index] = str[i];
                index += 1;
            }
        else if (isdigit(str[i]))
            {
                if (bool == 1)
                    {
                      count += 1;
                    if (count < 3)
                        {
                            result[index] = str[i];
                            index += 1;
                        }
                    }

                else
                    {
                        result[index] = str[i];
                        index += 1;
                    }
            }
        else
            {
                bool = 0;
                result[index] = str[i];
                index += 1;
            }

    }
    str[a] = '\0';
    return result;
}

This code does the following: it turns the string ab+0.16516=0.123 into ab+0.16=0. but it should be in ab+0.16=0.12
Is it possible to correct it without much changing the essence of the code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2018-07-12
@samsungovetch

Very complex code, a lot of unnecessary checks.
But at first glance, you do not reset count after cutting off the first digit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question