Reputation: 11
I have been working on an assignment for class and I keep getting an error I cant see to fix. Heres a portion of my code.
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
const int SIZE = 444;
int main()
{
char person1a[SIZE], person1b[SIZE], person2a[SIZE], person2b[SIZE], person3a[SIZE], person3b[SIZE],
person4a[SIZE], person4b[SIZE];
inData >> person1a[SIZE], person1b[SIZE], person2a[SIZE], person2b[SIZE], person3a[SIZE], person3b[SIZE], person4a[SIZE], person4b[SIZE];
return 0;
}
There is more to the code but i've narrowed the problem down to these lines. No matter how i seem to arrange them or what operators i use i always get a stack error at the first array. I've tried the obvious thing, to me at least, such as
inData >> person1a;
inData >> person1b;
etc
inData >> person1a >> person2b >> etc
and so on but I just cant get past this error.
Am I missing something obvious here, and if i am can anyone help me out?
For the record i know there are several topics about this already but im only taking my first programming class in school now and all the other topics have so much extra packed into them I cant understand it.
Upvotes: 1
Views: 300
Reputation: 254461
inData >> person1a[SIZE]
Assuming that inData
is some kind of std::istream
or similar, that streams a single character into element SIZE
of the array. Since that is the size of the array, and valid indexes are in the range [0,SIZE-1]
, it writes beyond the array causing stack corruption.
If you intend to read a string, then read into the array itself:
inData >> person1a
Of course, this will also cause corruption if the user enters too many characters, so use std::string
to store strings, rather than messing around with character arrays.
Also, to stream into more than one thing, chain >>
:
inData >> person1a >> person1b >> ...;
Your code uses the comma operator, meaning that you're only actually streaming into person1a
, and the rest of the statement has no effect.
Upvotes: 2
Reputation:
you are breaching the array boundaries when you access person1a[SIZE]
etc
Array indecies are 0-based, therefore the largest index is SIZE-1
not SIZE
Upvotes: 2
Reputation: 206526
Your array is declared as:
char person1a[SIZE];
So valid subscripts while accessing the array are 0
to SIZE-1
With the statement:
inData >> person1a[SIZE], person1b[SIZE], person2a[SIZE], person2b[SIZE], person3a[SIZE], person3b[SIZE], person4a[SIZE], person4b[SIZE];
You are writing one past the memory allocated for each of the arrays.
Since, You are using C++ you should use std::string
rather than c-style arrays.
It saves you all such problems and provides all the functionality that an character array provides you.
Upvotes: 2