简体   繁体   中英

Inputting numbers in char array

In reference to this problem I need to input a 100 digit number in the program and perform operations on it. I figured I would use a char array to do it.

I wrote this code after trying for some time.

 int main()
 {
 //int cases=10;

//while(cases--)
//{
    int i;
    char totalapples[102];
    //char klaudia_apples[200] , natalia_apples[200];

    for(i=0;totalapples[i]!='\0';i++)
    {
            cin>>totalapples[i];
    }

    //cin>>moreapples[200];
    //cout<<moreapples[200];

    while(i--)
    {
      cout<<totalapples[i];
    }
//}

    return 0;
  }

When I run this, I get the following result:

Input : 1234657891234567981345698
Output : 987564321

Can anybody tell what is happening??

Your program invokes undefined behavior. Despite the fact the char array contains undefined values you attempt to read from it using

totalapples[i]!='\0'

in your for loop. Instead, read the whole string into a std::string :

string totalApplesStr;
cin >> totalApplesStr;

Now you can iterate over totalApplesStr :

for (char c : totalApplesStr) {
     /* Do whatever you need to */
}

Or, if that isn't a logical error in your code, you can iterate from the end to the beginning:

for (auto it = totalApplesStr.rbegin(); it != totalApplesStr.rend(); ++it) {
    /* Do whatever you need to */
}

Use std::string instead of a char array.

You may then use std::tranform to convert to a vector of int to do your big number computations.

You attempt to test values from an array that has not been initialized yet.

Although a char array is the least safe method you could use for this, you could fix it with an initializer:

char totalapples[102] = {0};

Also, your second loop will print the result backwards. Try incrementing to i , not decrementing from i .

You new initialize your counter/index. And there are many other improvement to be done, but your code was short

#define ARRAY_SIZE 102

int main {
    char totalapples[ARRAY_SIZE];
    unsigned int i = ARRAY_SIZE;
    i = 0;
    while (i < ARRAY_SIZE)
    {
        cin>>totalapples[i]; // range is 0..101
        i++;
    }    

    i = ARRAY_SIZE;
    while (i > 0)
    {
        cout<<totalapples[i]; // range is 0..101
        i--; 
    }   
}

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