Reading the rest of a string after a certain character

So what I am trying to do is have the program read a txt file, and have it spit out the list of strings after the @ sign in a new file.

So for example if I have a file named Emails.txt, containing adfd@yahoo.com
The program would spit out @yahoo.com in a new file, and continue to read the list of emails and repeat this process until eof.

For some reason it seems to be giving me a segmentation fault, which I have no idea how to work around.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 #include<iostream>
#include<fstream>

using namespace std;

int main() {

  string STRING;
	ifstream infile;
	ofstream outfile;
	outfile.open("myEMAILS.txt");
	infile.open ("domains.txt");
        while(!infile.eof())
        {
            int atsign;
	        getline(infile,STRING);
            for (int i = 0; i < STRING.size(); i++) //checks for the emails char length.
                {

                    if(STRING[i]=='@')
                    {
                        atsign=i; //assigns atsign where the STRING has @ char
                        break; //skips this for loop and goes to next for loop
                    }
                }
            for(int y=atsign;atsign<=STRING.size();y++)
                {
                    outfile<<STRING[y]; //write down the rest of the string starting at @ sign
                }

                    outfile<<"\n"; //after loop is done skip a line in the file.

        }
 infile.close();
    outfile.close();
        }





What happens if the '@' is not found?

string offers functions that simplifies the problem:

http://www.cplusplus.com/reference/string/string/find/
http://www.cplusplus.com/reference/string/string/substr/
you need to #include <string> because you use std::string and std::getline.

string STRING; usually all uppercase letters means that its a constant you should use lowercase and a descriptive name.

1
2
	outfile.open("myEMAILS.txt");
	infile.open ("domains.txt");
just out of curiosity isn't this backwards? Shouldn't the infile be myEMAILS and the outfile be domains?

while(!infile.eof()) looping on eof is almost always wrong it should be more like while (getline(infile, STRING))

for(int y=atsign;atsign<=STRING.size();y++) should look more like this for (int y = atsign; y < STRING.size(); y++)
For the outfile.open("myEmails.txt") it has the domains and such, I was just too lazy to change the file names.

But I'll try and see if anything works thanks for your suggestions
Thanks for the suggestions it worked.

But it seemed to have a NULL symbol at the end of each domain name
why is this?

@yahooNUL
@gmailNUL
Nvm I fixed it
Topic archived. No new replies allowed.