954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to cin.ignore Punctuation

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;
}
Tmy
Newbie Poster
3 posts since Dec 2008
Reputation Points: 16
Solved Threads: 0
 

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.

William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
 

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

Tmy
Newbie Poster
3 posts since Dec 2008
Reputation Points: 16
Solved Threads: 0
 

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;
}
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
 

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

Tmy
Newbie Poster
3 posts since Dec 2008
Reputation Points: 16
Solved Threads: 0
 

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

Chris

Freaky_Chris
Master Poster
702 posts since Apr 2008
Reputation Points: 325
Solved Threads: 118
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You