Restrictions on the getline C ++

0

The program consists of collecting the names of people, (only their names, not last names) showing them by screen, until finding a string that is 'END'.

Program format: (first name, last name)

Example:

Manuel, Perez
Pepe, Geneva
Lola, Flowers
 END

#include<iostream>
#include<string>
using namespace std;

int main()
{
  string aux;
  getline(cin,aux,',');

  while(aux != "FIN")
  {
   cout << aux;
   getline(cin,aux,',');
  }

return 0;
}

Since we only want the name, we use a

  

getline (cin, aux, ',')

I end up finding a comma, excluding this one. However, the moment we enter 'END', the getline will wait for a comma and until it is entered the program will not end.

Any suggestions to fix this?

    
asked by Vendetta 27.10.2018 в 20:55
source

1 answer

1

The solution is to receive the entire string belonging to the line, and treat this string up to the character ','. You can use the following code:

#include<iostream>
#include<string>
#include<cstring>
using namespace std;

int main()
{
    string aux;
  getline(cin,aux);

  while(aux != "FIN")
  {


   std::string::size_type filePos = aux.rfind(',');
   std::string name = aux.substr(0,filePos);

    cout << name;
   getline(cin,aux);
  }
  cout<<aux;

    return 0;
}
    
answered by 28.10.2018 / 17:38
source