Extracting data from a file

Hi there,

Well my assignment is to pull data from a census file, namely enter a name and extract the history of it's popularity. The txt file has each name along with 11 sets of data, space between each and the name. I have this so far but I'm stuck and the program fails to execute:

So I've muddled around with it and actually got it to work! BUT I can't figure out how to add a "Name not found." clause if it cannot find the name.

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

using namespace std;

int main(int argc, char *argv[])
{
string word, line;
int x;


cout << "** Name Popularity Program **" << endl;

ifstream file;
file.open("firstnames.txt");

cout << "Please enter the first name:" << endl;
cin >> word;


if (!file.good())
cout << "Error: File not found!" << endl;

else
{

while (!file.eof())
{
getline(file, line);
x = line.find(word);

if (x!=string::npos)
cout << line << endl;

}
}



system("PAUSE");
return EXIT_SUCCESS;
}
Last edited on
Simple solution is to introduce a flag

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool nameFound = false;
while( !file.eof() )
{
    getline( file, line );
    x = line.find( word );

    if ( x != string::npos )
    {
        cout << line << endl;
        nameFound = true;
    }
}

if( false == nameFound )
    cout << "Error: Name not found" << endl;
Topic archived. No new replies allowed.