Iam trying to print out an array using a for loop and it works but there is extra numbers after it I don't know how they got there or how to make it go away so if you guys could help me out I would greatly appreciate it.
[#include <iostream>
using namespace std;
int main(){
string name1;
cout<< " Enter a name: ";
cin>> name1;
string name2;
cout<< " Enter a name: ";
cin>> name2;
string name3;
cout<< " Enter a name: ";
cin>> name3;
string name4;
cout<< " Enter a name: ";
cin>> name4;
string name5;
cout<< " Enter a name: ";
cin>> name5;
string name6;
cout<< " Enter a name: ";
cin>> name6;
string name7;
cout<< " Enter a name: ";
cin>> name7;
string name8;
cout<< " Enter a name: ";
cin>> name8;
string name9;
cout<< " Enter a name: ";
cin>> name9;
string name10;
cout<< " Enter a name: ";
cin>> name10;
for (int i = 0; i<= 10; i++)
{
cout << Name[i]<< endl;
}
-----------------------------------------------------------------------------
-And I get this as the output:
Enter a name: 1
Enter a name: 2
Enter a name: 3
Enter a name: 4
Enter a name: 5
Enter a name: 6
Enter a name: 7
Enter a name: 8
Enter a name: 9
Enter a name: 0
1
2
3
4
5
6
7
8
9
0
\370\277_\377u
\346v\316\243
Program ended with exit code: 0
The problem is that you check i <= 10
You only have 10 elements in you array so the last index is 9
You also print out the content of Name[10] which does not exist.
Simply change that i <= 10 to i < 10;
One question, why don't you just put the names in the array?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
int main()
{
std::string Name[10];
for(int i = 0; i < 10; ++i) {
std::cout<< " Enter a name: ";
std::cin >> Name[i];
}
for(int i = 0; i < 10; i++)
std::cout << Name[i] << std::endl;
}