ok this is getting frustrating. I'm trying to have the user enter in a number of lists and have it outputted accordingly. I don't see why this program is crashing so easily.
#include <iostream>
#include <string>
using namespace std;
int main(){
string x[2];
int y= 0;
for(y=1; y=2; y++){
cout << "Please Enter Students name" << endl;
cin >> x[y];
}
}
Im inputting the string for x[1] correct? Thats what the loop tells me but when i enter the name. It doesnt move to y[2] It just crashes. I don't understand.
for(y=1; y=2; y++){
The very first time this is executed, y is assigned the value 1.
Before going on to execute the body of the loop, the condition y=2 is evaluated. This assigns the value 2 to y, and since this is a non-zero value the expression evaluates as true.
Now the body of the loop is executed, and it attempts to execute cin >> x[y];, since y is 2, this is accessing the 3rd element of the array which is beyond the boundary of the array.
The code would be better written something like this;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
constint size = 2;
string x[size];
for (int y=0; y<size; y++)
{
cout << "Please Enter Students name" << endl;
cin >> x[y];
}
}