Arrays and output

I am attempting to use an array but when I do the first character is always missing. Help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int name()
{
    char name[8];
    cout<<"Please enter your name"<<endl;
    cin.get();
    cin>>name;
    cout<<"Your name is "<<name<<"!"<<endl;
    cin.get();

}

int main()
{
    name();
    cin.get();
    return 0;
}
You have put "cin.get()" before "cin >> name"; which means that the character that cin.get() is extracting from the input stream is not being caught by cin; so you're not getting the first character in name.

That is probably not a particularly good way of filling an array. What if they enter a name of 9 or more characters?
Perhaps you could do it like this:
1
2
3
4
/* replaces lines 8 and 9 */
for (int i = 0; i < int(sizeof(name) / sizeof(*name)); i++) {
    name[i] = cin.get();
}


I would also recommend a bigger array; I myself have an 11 character first name :)
cin.getline ( name, 8 );
Topic archived. No new replies allowed.