ignoring a comment line beginning with #

Hi,
my program had a requirement to ignore an input beginning with a # sign. The input is entered by user from keyboard. I wanted to know how to use cin.ignore to achieve this.


#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <limits>
#include <stdio.h>

using namespace std;

int main()
{
string str;
cout<<"Enter the string"<<endl;
cin >> str;
cin.ignore( /*I dont know how to use this part*/);
cout<<"Entered string: " <<str <<endl;
}

The output:
Enter the string
# Comment
This is the # comment
string.


Answer:
This is the string.
1
2
if (str[0] == "#")
  //... 
The 'str' variable will get some string data in it,in c++ it doesnt get cleared,so to remove the data from the stream one has to use the parameter cin.ignore() to replace the data in the stream with the blank spaces.
Here is the link to the arcticle which can help you
-->http://www.cplusplus.com/forum/articles/6046/
but this just removes comment line at the beginning of the sentence right...? But in the example above, it could be anywhere in the input.
my program had a requirement to ignore an input beginning with a # sign


but this just removes comment line at the beginning of the sentence right...? But in the example above, it could be anywhere in the input.


To remove it if it contains the "#" sign use the std::string.find() method:
http://www.cplusplus.com/reference/string/string/find/
Get input using getline()

1
2
3
4
5
string s;
cout << "Enter the string> ";
getline( cin, s );
s.erase( s.find_last_not_of( '#' ) + 1 );
cout << "Without #comment, the string you entered is: " << s << endl;

This code assumes that the character '#' cannot appear in a valid statement. Otherwise it is a bit trickier.

Hope this helps.
Actually this is not ignoring the comment line.. I get the same output..
I got the answer. Thank you all for you help. Here is the code finally..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

int main ()
{
  string str;
 
  cout << "Enter the string> ";
  getline( cin, str );
  unsigned found = str.find('#');
  if (found!=std::string::npos)
    str.erase(found);
  else
    str.clear();   

  cout << str << "\n";

  return 0;
}

Last edited on
¿? ¿did you bother to test it?
yes.. Here is the answer:

1
2
Enter the string> Hello #comment    
Hello



Of course i handled the else part later in my code where i added some other piece of code instead of str.clear();
Topic archived. No new replies allowed.