Thread: C++ cin.getline help

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    12

    C++ cin.getline help

    This is part of my code and i'm stuck on the cin part i dont exactly remember how it went for arrays... i need to cin a name that contains whitespace but when i do that the program starts looping forever...or skips an entry. Now i remember its something like cin.getline() but i can't figure it out any help would be greatly appreciated thx!
    Code:
    #include <iostream>
    #include <string>
    #include <iomanip>
    
    using namespace std;
    
    const int MAX = 40;
    
    
    void bubbleID(int id[], int max);
    void bubbleName(string name[], int max);
    void dsply();
    
    
    int main()
    {
    	int id[40];
    	string name[40];
        char choice;
        bool running = true;
        int count = 0;
        
        while(running)
    	{
    		dsply();
            cin >> choice;
            
            switch(choice)
            {
                case 'A':
                case 'a':
                    cout <<"\n"<< count + 1 << ":\n\nEnter Student's CWID: ";
                    cin>>id[count];
                    cout << "\nEnter Student's Name: ";
                    cin>>name[count];
                    break;

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    do not use >> for entering strings with spaces - this operator stops on white space
    use getline for this purpose
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  3. #3
    Registered User
    Join Date
    Feb 2008
    Posts
    12
    Code:
    getline(cin,name[count++]);
    so like that right? but now that i put it in after i enter the number it just ends the program..

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,794
    your >> operator leaves '\n' in the input stream

    that is read by getline

    use cin.ignore between using of operator >> and getline
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin.getline help
    By Cool Dude 2k in forum C Programming
    Replies: 2
    Last Post: 07-27-2005, 06:55 PM
  2. cin.getline and msgrcv
    By osal in forum C++ Programming
    Replies: 2
    Last Post: 03-17-2005, 12:01 PM
  3. difference between getline and cin.getline
    By bartinla in forum C++ Programming
    Replies: 3
    Last Post: 11-13-2004, 09:47 AM
  4. problem with cin.getline()
    By Waldo2k2 in forum C++ Programming
    Replies: 8
    Last Post: 05-28-2002, 05:53 PM