Hey everyone- I am having trouble with structs...grrrr. I am trying to ignore the - sign in the beginning of the number so I can compute the average. I cant seem to remember how to just ignore the sign or whatever, without using cin.ignore since the number is already read in. Also my average function isnt working right even with the positive numbers. Basically structs confuse the hell out of me! Please give advice if possible! Thanks!
Overview:
so I am reading in from a file long integers. I am reading them into a string function and then breaking the numbers up and storing them in an int array. I can convert from string to int and store the numbers ok, I just need to ignore the - sign when storing them in the array, so I can use the numbers to calculate average.
Ex:
Code:
-123456789
average needs to be (1+2+3+4+5+6+7+8+9) / 9
Thanks!
Code:
struct bigint
{
string nstr; //string representation of the big integer n
int n[MAX]; //array representation of the n
int len; //# of digits in n
bool neg; //flag to indicate sign of n, true if negative, false otherwise
};
int main()
{
int n;
bigint number[50]; //number can store the string of a big integer, the array of
//numbers, the length of the numbers, and the sign of each number
ifstream infile; //infile represents the input data file
string ifilename; //name for input filenames
int count=0; //counter for # of numbers in input file
n = 0;
int s;
int average;
cout << "Please enter input file name" << endl;
cin >> ifilename;
infile.open(ifilename.c_str());
infile >> number[n].nstr;
while (!infile.eof())
{
number[n].len = number[n].nstr.length();
n++;
infile >> number[n].nstr;
}
cout << endl << "The " << n << " bigints read were" << endl;
for (int i = 0; i < n; i++)
{
cout << number[i].nstr << endl;
}
cout << endl;
for (int s=0; s < n; s++)
{
for (int j=0; j < number[s].len; j++)
{
number[s].n[j] = number[s].nstr[j] - '0';
cout << number[s].n[j];
average = average + number[s].n[j];
}
cout << endl;
average = average / number[s].len;
cout << average;
}
return 0;
}