Thread: cin and getline() problems....

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    20

    cin and getline() problems....

    Hi,

    I have some problems with this code:

    Here I have the code for a function that enables the user to add name and numbers in my phonebook. However when i execute the function the program skipps the first name. Let's say that I choose val3 to be 2 and thus i get to input 2 names and 2 numbers etc. it will look like this:

    People to add, input number between 1 and 100: 2
    1*Name:
    2*Telephone number: 073445263
    3*Name: adampqmaba
    4*Telephone number: 07331337


    1* --- Just a blank here nothing to add or input
    2* --- here i can insert any telephone number.
    3* --- here the program acts as it should do.
    4* --- same here the second time.

    I have tried using cin.ignore(1000, '\t'); after my cin phrase. The program then goes into an infinite loop where i can input any numbers or letters just like a notepad. nothing like name: or number: is shown.




    Code:
    void addP(){
    
    	telefon Phone_data[100];
    	int val3;
    
    	ofstream utfil;
    	utfil.open("Phonebook.txt", ios::app);
    main:
    	cout << "People to add, input number between 1 and 100: ";
    	cin >> val3;
    	
    	if (val3>100 && val3<0){
    	goto main;
    	}
    
    	for (int i=0; val3>i; i++){
    		
    		
    		cout << "Name: ";
    		getline(cin, Phone_data[i].namn);
    		cout << endl << "Telephone number: ";
    		getline(cin, Phone_data[i].nummer);
    
    		utfil << Phone_data[i].namn << '\t' << '\t' << Phone_data[i].nummer << endl;
    		
    	}
    
    utfil.close();
    }

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    That is because it is waiting for tab, bud. Have it ignore the '\n' char. Not the '\t' char.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    20
    Thank you master!! you solved my problem as usual

  4. #4
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    All those years of programming until dawn and losing out on sleep... and all those times I opted to finish a project over going out on a date finally paid off!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with getline
    By MarlonDean in forum C++ Programming
    Replies: 5
    Last Post: 07-01-2008, 05:04 AM
  2. vectors and cin, getline?
    By barneygumble742 in forum C++ Programming
    Replies: 9
    Last Post: 07-02-2005, 01:48 AM
  3. What's the Diff between getline and cin?
    By KneeGrow in forum C++ Programming
    Replies: 4
    Last Post: 05-23-2003, 04:49 AM
  4. getline with string class in Borland C++
    By johnnyd in forum C++ Programming
    Replies: 6
    Last Post: 03-08-2003, 02:59 PM
  5. Replies: 5
    Last Post: 03-01-2003, 10:23 PM