I'm having a little trouble finding multiple occurrences of a string in a file. I have a txt file and I have to find e-mail addresses out of it. I open the file with ifstream, and use getline to read in each line. I then use str.find(str1, pos) to find the '@' symbol in the file. I just can't figure out how to pull the entire address out and not just the @ symbol. Any tips?
Help finding a string in a file
Collapse
X
-
is there a reason you are going line by line? if not you can just step through the file via the spaces ifile>>MyString ; then check the string to see if there is a @ symbol in it. If so, MyString = e-mail address (assuming all items that have @ is an e-mail).
You can also take the location returned from the find function and keep on stepping back until you reach a ' ' or the string[0]. Then you would have to step forward until you hit a ' ' or a '\n'. -
I would use an iterator and step through until I found the @. This is one past the address so this works as an end iterator with the copy algorithm. So, you just copy from begin() to your iterator pointing at the @.Comment
-
Well, I changed my algorithm. I'm now searching for "mailto:". This is what I have (it doesn't work).
string sub;
int found_position = 0;
//string s = " ";
char temp_s[200];
string found_email = " ";
char temp_sub[50];
while (! instream.eof() )
{
instream.getlin e(temp_s, 200); //reads in string of 200
str1 = temp_s; //use the constructor of string to build a string
sub = temp_sub;
found_position = str1.find("mail to:"); //tell me where "mailto:" is
sub = str1.substr(fou nd_position + 7); //string after mailto:
if(found_positi on >= 0)
{
for (unsigned int index = 0; index < sub.length(); index ++)
{
if(sub[index] == '"') //checks for spaces (end of address)
{
break;
}
found_email += sub[index];
}
cout << found_email << endl;
emailList.push_ back(found_emai l);
}
}
It doesn't work :-( Any tips?Comment
-
First use the code tags provided. When you hit reply there are reply guidelines to the right which provides the description of how to use them. Second could we see what your input file looks like (just a few lines will do), or how the assignment describes what the input file should be like. Third "It doesn't work" isn't a very good description of the problem. Does it not compile? Does the program crash? Does your vector contain 0 items? Here is a couple of items i see.
In the input file is it mailto:<EmailAd dyHere> or mailto: <EmailAddyHer e> (notice the space).
if you have mailto: <emailaddy> you will exit the loop without copying the string items because you have a space between mailto: and the e-mail address.Code:if(sub[index] == "") // does that even compile? you are checking for a char so if(sub[index] == ' '); use single quotes when checking chars
Comment
Comment