Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
int main()
{
    int length;
    cout << "Enter the no. of names: ";
    cin >> length;
    string *names = new string[length];
    //cout << "\n names= "<<names;
    for (int i(0);i<length;i++)>
    {
        cout << "\nEnter "<<i+1<<" name: ";
        getline(cin,names[i]);
    }
    
    return 0;
}
Posted
Updated 24-Aug-15 0:37am
v2

My previous response was incorrect.

The issue is that cin only reads the next token up to the first whitespace character. In this case the whitespace is the end of line character(s) after the number, which need to be consumed before the first call to getline. You can clear the input buffer by calling cin.get().

Also, you cannot input a name containing spaces for the same reason (the space acts as a token delimiter), so you have to use getline to read the entire string.
 
Share this answer
 
v3
Comments
the_beginner 24-Aug-15 6:55am    
thanks for ur answer.
but names[i] = new string; is giving compile time error:Invalid conversion from string* to char
By the way how come this code works if i use
cin >> names[i] instead of getline(cin,name) (but i can't enter names with spaces)
Richard MacCutchan 24-Aug-15 7:20am    
Quite so; answer updated.
the_beginner 24-Aug-15 7:23am    
Thanks Richard sir.
You have a problem with
C++
cin >> length;

leaving the line terminator in the buffer.

Input with cin is a bit tricky, anyway, a quick fix would be adding cin.ignore(); immediately before it to eat up the line terminator.
C++
cin >> length;
cin.ignore();



By the way, Richard gave you the good advice of using vector<string> instead of explicitely dynamically allocated array. As matter of fact, in your code you never release the allocated memory.
 
Share this answer
 
v2
Comments
the_beginner 24-Aug-15 7:15am    
Thanks it worked, but just a small query why code worked when using cin instead of getline.
Iam using delete[] names; to release memory at the end of code

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900