remove the substring after a #

HI everyone ,so i am trying to read out from a text file.
there are 2 columns. 1st column has the instructions that i need to program later on and 2nd column that has the values (string ). so in the 2nd column some of it will have the # sign at the end just to symbolize a comment line. so every time we are reading the file we are suppose to ignore all of the words after #. i have tried to use erase but it gives me an error after i execute. i have successfully read the file but i am not sure how to ignore the substrings after # please help to advise


the text inside the file
1
2
3
4
  init 32 #test line
  add 5 #this too
  delete 10
  add 2


my code is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
iss>>instruct;
		getline(iss,data);

	//string hashsign = data.substr(0, data.find("#"));
	data.erase (data.find("#"),data.length());
	

		if(instruct=="init")
		{
		cout<<"This is for init - "<<data<<endl;		
		}
		else if(instruct=="add")
		{
		cout<<"This is for add - "<<data<<endl;
		}
Hi,

std::getline takes a 3rd parameter which is the delimiter :+)

https://en.cppreference.com/w/cpp/string/basic_string/getline
OMG silly me , i didnt thought of that , works perfect now. Thank you very much
The problem is that std::string::find returns std::string::npos when token is not found. Passing std::string::npos as first argument to std::string::erase causes an exception to be thrown because it is not a valid position in the string. To make this work you would have to check that the position is not equal to std::string::npos before passing it on to std::string::erase.

1
2
3
4
5
std::size_t hashPos = data.find('#');
if (hashPos != std::string::npos)
{
	data.erase(hashPos, data.length());
}


Another approach is to use std::find, which uses iterators instead of indices, and the iterator version of std::string::erase. This slightly simplifies the code because std::find returns the end iterator if the token is not found, and erasing all elements in the range (end, end] is a totally valid operation that will do nothing so you don't need any additional checks.

 
data.erase(std::find(data.begin(), data.end(), '#'), data.end());
Last edited on
Topic archived. No new replies allowed.