Reputation: 11
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??
Upvotes: 0
Views: 49
Reputation: 89
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--;
}
}
Upvotes: 0
Reputation: 15229
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 */
}
Upvotes: 1
Reputation: 4873
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
.
Upvotes: 0
Reputation: 7996
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.
Upvotes: 0