简体   繁体   中英

Subtraction in a while loop. C++

I have this code snippet. I need to subtract numbers from a byte stream (which is already being tokenized by a , ).

The problem is, when I do sub = sub - atoi(pchNew) it gives the sum of all the numbers in negative. Unfortunately, subtraction is not the same/simple as addition and multiplication.

My question is: How do we subtract numbers in a while loop?

else if(strcmp(pch, "sub")==0)
{
    sub = 0;
    pch = strtok(NULL," ");

    pch = strtok(pch," ");
    //printf ("------->%s   :",pch);
    pchNew = strtok(pch, ",");
    do
    {
        sub = sub - atoi(pchNew);

        //write(STDOUT_FILENO,"IN LOOP\n",9);
        pchNew = strtok(NULL,",");

    } while(pchNew !=NULL);

    printf("The Subtraction is= %d\n", sub);
    fflush(stdout);
}

'Update:'

Input:

Client> sub 4,3,4,5

Output:

Server> The Subtraction is= -16

Thanks in Advance, Safeer

You want to take the first one and subtract the next from it right?

else if(strcmp(pch, "sub")==0)
{
pch = strtok(NULL," ");

pch = strtok(pch," ");
//printf ("------->%s   :",pch);
pchNew = strtok(pch, ",");

sub = atoi(pchNew);
pchNew = strtok(NULL,",");

while(pchNew !=NULL)
{
sub = sub - atoi(pchNew);

//write(STDOUT_FILENO,"IN LOOP\n",9);
pchNew = strtok(NULL,",");

};

printf("The Subtraction is= %d\n", sub);
fflush(stdout);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM