I am new in programming,
basically in this program, it takes input from user and storing in array, 5 elements. After loop ends it should give the elements back but it seems that the last line is not working.
include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i ){
cin>>guess[size];
}
cout<<guess[size];
return 0;
}
CodePudding user response:
guess[size]
is out of bounds. The last valid index in an array with size
elements is size-1
. Further, string guess[size];
is not valid C when size
is not a constant expression. At the very least it should be const int size = 5;
. You wrote a loop to take input and you also need a loop to print all elements.
This is the correct loop to read the input:
const int size=5;
std::string guess[size];
for (int i=0; i < size; i ){
std::cin >> guess[i];
}
CodePudding user response:
You can modify it so that both input and output should use i as the loop subscript.
//cover #
#include<iostream>
using namespace std;
int main(){
int size=5;
string guess[size];
for (int i=0; i<size;i ){
cin>>guess[i];
}
for (int i = 0; i < size; i) {
cout<<guess[i];
}
return 0;
}
CodePudding user response:
Use Range based Loops when You want to Print whole array, so you won't get an "Out-Of-Bounds" error. Because the Index in array are Zero Based Always remember the last index is (length_of_array - 1)
using namespace std;
int main()
{
int size = 5;
string guess[size];
for (int i=0; i<size;i )
{
cin >> guess[i];
}
// range based loop
for (int i : guess)
{
cout << i << endl;
}
return 0;
}