ProgrammingNoob
ProgrammingNoob

Reputation: 49

How to add up numbers using strtok?

I am trying to add up chars together after every commas using strtok but i dont know where to start? where is the variable storing the actual value of the inputString? tok += tok; doesnt really make sense but thats all i could think of atm. i also have a separate function that converts strings into int, do i add that in here too? assuming the function is called char strint(void);

char addtotal (void)
{
    char inputString[LINE_LEN + EXTRA_SPACES];
    char *tok;
    char com[2] = ",";

    printf("Enter numbers to be tokenized using commas: \n");

    if (fgets(inputString, LINE_LEN + EXTRA_SPACES, stdin) == NULL)
    {
        printf("ERROR!\n\n");
        return EXIT_FAILURE;
    }

    if (inputString[strlen(inputString) - 1] != '\n')
    {
        printf("BUFFER OVERFLOW!\n\n");
        return EXIT_FAILURE;
    }

    inputString[strlen(inputString) - 1] = 0;

    tok = strtok(inputString, com);

    while(tok!=NULL)
    {

        printf("%s \n", tok);

        tok = strtok(NULL, com);

    }


}

Upvotes: 1

Views: 614

Answers (1)

J. Lee
J. Lee

Reputation: 71

I'm not completely sure what you're trying to achieve here, but I assume you're trying to do some arithmetic operations between comma-separated integers.

int addtotal(void)
{
    int result;
    ...
    tok = strtok(inputString, com);

    for (result = 0; tok != NULL; )
    {
        result += atoi(tok);
        tok = strtok(NULL, com);
    }

    return result;
}

You can do it like this. I didn't test it, but it should work.

Upvotes: 0

Related Questions