Find @ in a text file using <fstream> and output


I had a a post for this already but I have completely rewritten my code so here we go again. The purpose of this program is to simply read a .dat / text file and find all strings with the "@" character. It is then supposed to use the ofdata stream to write these strings to another text file. My code is below. For some reason it only reads the first string and stops at the first space as of this post. I am using pos to ensure it grabs the entire string that contains "@". Also, if you post I am a complete newb and I give you guys a lot of props for helping other, but please do not reply with anything that someone who has been learning this for 4 weeks now cannot understand. Thanks and hope someone has any ideas.

code below:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main ()
int pos;
int lens1;
string s1;
string email;
ifstream indata;
ofstream outdata;"G:\\mail.dat");"G:\\list.dat");

if (! indata)
cout<< "The file mail.dat cannot be opened" <<endl;

if (! outdata)
cout<< "The file list.dat cannot be opened"<<endl;

if (indata.is_open())

while (! indata.eof())// read the entire file including white space till the end of the file

indata >> s1; // read input data and convert to variable s1

pos= s1.find("@"); // find the "@" in the string

lens1 = s1.size(); // find the size of the string

if (pos<= lens1 && pos>lens1) // if the "@" character is within the measured sting than cout as s1

cout<< "The file Mail.dat contains the following e-mail address"<< endl;
cout << s1 << endl;
outdata << s1;


indata.close(); // close the indata file
outdata.close();// close the outdata file


return 0;
Please use code tags when posting

Also if your going to ask questions about file I/o then a sample of the file would be helpful

while (! indata.eof()) this is generally considered bad programing usually you would do something like this. while (indata >> somevar){}

or while(getline(indata, somestring))

your while loop has no brackets after it so the while only applies to the next statement indata >> s1; so you input a single string until the end of file is found and then check the last string to see if it contains a @ so you are only checking the last string in the file for a @

For some reason it only reads the first string and stops at the first space as of this post

The >> operator uses whitespace as a delimiter so when it encounters a space or newline it stops extracting charaters

you can use getline if you don't want to use the space as a delimeter
Last edited on
Topic archived. No new replies allowed.