Member Avatar for Tmy

how can i use cin.ignore to ignore every character up to and including a specified character – for example a full stop, ’.’ or a comma ',' ??
for example if the person entered Tom Jones.
the program needs to igonre the full stop

please help

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


int main()

{
 	string name, surname;

   	cout <<"what is your name? ";
   	cin >> name >> surname;


	cout << surname << "," << name << endl;

	return 0;
}
William Hemsworth commented: Nice first post :) +6

Recommended Answers

All 5 Replies

Well, theres a few ways you can do this, one method which I would probably use would be to read in the names, and manually remove all punctuation. To do that, you simply loop through each character, check if it is punctuation, if so, then erase it like this:

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

void removePunct(string &str) {
  for (size_t i = str.length() - 1; i; --i)
    if ( ispunct(str[i]) )
      str.erase( i );
}

int main()
{
  string name, surname;

  cout << "what is your name?" << endl;
  cin >> name >> surname;

  removePunct( name );
  removePunct( surname );

  cout << surname << ", " << name << endl;
}

Hope this helps.

Member Avatar for Tmy

hi there thanks for your reply it works perfect, but is there a simpler way as i have not leant about the void possible embedding something like this "char punct[2] = {'.','!'};" your patience’s is appreciated

regards terry

Well, the void is there to make a function, to give more simple code. But to do it without the function is just as easy.

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

int main()
{
  string name, surname;

  cout << "what is your name?" << endl;
  cin >> name >> surname;

  for (size_t i = name.length()-1; i; --i)
    if ( ispunct(name[i]) )
      name.erase( i );

  for (size_t i = surname.length()-1; i; --i)
    if ( ispunct(surname[i]) )
      surname.erase( i );

  cout << surname << ", " << name << endl;
}
Member Avatar for Tmy

thanks for taking the time but just one last thing is there any way to do it by using the cin.ignore??

No cin.ignore() is designed to clear everything before a given character or for a given length, not clear the given character.

Chris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.