arrays?

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;





string Name[10];
Name[0]= name1;
Name[1]=name2;
Name[2]=name3;
Name[3]=name4;
Name[4]= name5;
Name[5]= name6;
Name[6]=name7;
Name[7]=name8;
Name[8]=name9;
Name[9]=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

Your for loop is looping one too many times.
1
2
3
for (int i = 0; i<= 10; i++){
    cout << i << endl;
}

Prints
0
1
2
3
4
5
6
7
8
9
10


instead you may want to use i < 10 instead of i <= 10

But why is it printing random numbers? You are accessing a point beyond your array, this results in undefined behaviour.
Last edited on
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;
}
Last edited on
Topic archived. No new replies allowed.