Hello,
im trying to make a program that reads from a file and sums up only the numbers.the numbers ar aranged like this in the file:
100er34 67 yyy 7
5 63 6
1

My problem is that the program sums up wrong,it sums some numbers twice when it see space.its supposed to sum like this:100+34+67+7+5+63+6+1=283 But it sums like this 100 + 34 +4?+67+7+7?+5+5?+63+3?+6+1 =297 What kan i do? And i have to use strpbrk().

Thanks

//
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
/*
    oppgave2.txt contains
    100er34 67 yyy 7
    5 63 6
    1


*/

int main(){

    ifstream inputFile;
    char input[81];
    char input2[81];
    char input3[81];
    char test[] = "0123456789";
    char *ptr;
    int sum = 0;
    //cout<<"her";
    inputFile.open("oppgave2.txt");
    if(!inputFile){
        cout<<"File error\n";


    }
    else{
        //inputFile>>input;




        while(!inputFile.eof()){

             inputFile.getline(input,81);

             ptr = strpbrk (input, test);

        while(ptr != NULL ){

            cout<<*ptr<<" ";

            sum += atoi(ptr);
            cout<<"sum: "<<sum<<" ";


            ptr = strpbrk(ptr+1,test);


        }
    }
        cout<<"\n sum:"<<sum;

    }

    inputFile.close();

    return 0;
}

strpbrk effectively returns the part of the string starting at the first occurence until the end of the string.
If you pass such a string to atoi it will return the first numeral and ignore everything after that.
Note that this numeral doesn't have to be 1 digit long but can be many more and you're not dealing with this in the right way because what happens is this:

input: 12345

ptr: 12345
atoi(strpbrk()): 12345

ptr+1: 2345
atoi(strpbrk()): 2345

ptr+1: 345
atoi(strpbrk()): 345

And so on.

You could get the length of the number simply by checking to what power of 10 it's greater or equal to, but that's not a proper way to do it since every number with some leading zeroes (which are discarded by atoi) would make your program fail.

The best approach in my eyes would be to add another loop after you've found a digit:
Save the first digit of a numeral (ptr[0]) in an int and then loop the next characters until you find a non-digit simply while multiplying the old int by 10 and adding the new digit each time you do find a new one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.