0

First time the program runs perfectly but second time it does not input string from the user i don't know why?

I think there is a problem in the getline(cin,str);but i can't resolve the problem

#include<iostream>
#include<string>

using namespace std;

int main(){
    string str;
    char check;
    do{
        system("cls");
        cout<<"Enter the number (sample : +92121234567(Must contain 12 characters)) : ";
        getline(cin,str);
        cout<<endl<<str;
    if(str.length() == 12){

        string countrycode = str.substr(0,3);

        if(countrycode == "+92"){

            string citycode = str.substr(3,2);

            if(citycode == "51"){
                cout<<endl<<"This number belongs to Islamabad";
            }else if(citycode == "42"){
                cout<<endl<<"This number belongs to Lahore";
            }else if(citycode == "21"){
                cout<<endl<<"This number belongs to Karachi";
            }else{
                cout<<endl<<"Unknown Number";
                cout<<endl<<"Remarks : ";
                cout<<endl<<"Unknown city code";
            }
        }else{
            if(str.substr(0,1) =="-"){
                cout<<endl<<"Unknown Number";
                cout<<endl<<"Remarks : ";
                cout<<endl<<"Wrong country code format";    
            }
            if(str.substr(1,2) !="92"){
                cout<<endl<<"Unknown Number";
                cout<<endl<<"Remarks : ";
                cout<<endl<<"Unknown country code"; 
            }   
        }
    }else{
        cout<<endl<<"Unknown Number";
        cout<<endl<<"Remarks : ";
        cout<<endl<<"Number is over 12 characters";
    }


    cout<<endl<<"Do you want to enter another number (y/n): ";
    cin>>check;
    //str.clear();
}while(check=='y'||check=='Y');

cout<<endl<<"End of Program. Bye!"<<endl;
system("pause");
return 0;

}

  • 3
    Possible duplicate of [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Algirdas Preidžius Aug 26 '18 at 09:10
  • `cin>>check;` reads only one character but you have to [ENTER] your input. Hence, the line-end `\n` stays in internal input buffer and becomes effective when `getline()` is called 2nd time. – Scheff's Cat Aug 26 '18 at 09:11
  • 2
    You should add ``cin.ignore();`` after ``cin>>check``, when you hit enter key, your program also reads \n as input. – unlut Aug 26 '18 at 09:13

1 Answers1

-1

use cin >> str; Dont know why, but getline does not work for me either.

christian
  • 110
  • 1
  • 2
  • 15