0

Hi,

I am using the following code to convert character array in file to integer.
However, the problem is that there is only one place in the file where it does not convert the character array to integer correctly.

Since my code is big, i am pasting the most relevant part.

if(c == 'n')
            {
                if((c=getc(fp)) == 'e')
                {
                    if((c=getc(fp)) == 't')
                    {
                        c=getc(fp);            // For the '_' after net.
                        arr1 = new char[3];
                        int i = -1;
                        while(1)
                        {
                            c=getc(fp);                // Get the number.
                            cout << "c = " << c << " ; ";
                            if(c == ';' || c == ' ' || c == ',' || c == ')' || c == '=' || c == '<')
                            {
                                cout << "c2 = " << c << " ; ";
                                break;
                            }
                            else
                            {
                                i = i + 1;
                                cout << "c1 = " << c << " ; ";
                                arr1[i] = c;
                            }
                        }
                        numo = atoi(arr1);
                        //sscanf (arr,"%d",&numo);
                        delete arr1;
                        keep.insert(numo);
                        cout << " NET num =  " << numo << endl;
                    }
                }
            }

in the file :

not( net_2584, net_2546);
    not( net_2585, net_2499);
    not( net_2586, net_2490);
    not( net_2587, net_2474);
    not( net_2588, net_2502);
    not( net_2589, net_2505);
    not( net_2590, net_2507);

It reads 2490 as 24900.

I do not understand why.
Is there a better way to convert a character array to integer when the size of character array is not known before hand.

Any help is appreciated. Thanks.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

I think the array: arr1 = new char[3];
is too small. why isn't it arr1 = new char[5]? I would set arr1[4]='\0' to ensure it gets interpreted as a c-string.

0

why are you doing that the hard way, such as one character at a time, when there are much faster, easier, and less error-prone ways, such as fscanf() . If your instructor requires you to do it that way, then do it. Otherwise you have just wasted how many hours??

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.