How do I only put the # of the line?

I have a program that searches through a list of names. The user is to input the name and the program finds the name and is supposed to say the # of the line the name is on, which is also included in the line as an int. Right now, it outputs the entire line which includes line line # (which is a rank subsequently), and a couple names. I am not using arrays yet. I want to thank you in advance for your time and feedback. How do I get it to only display the # at the beginning of the line which is both the rank and the line #?


int main()
{
//declare local variables
ifstream list;
string name;
cout << "Please enter a name, then press enter.";
cin >> name;
list.open("babynames2012.txt");
Babyname(list, name);
list.close();
return 0;
}

void Babyname(ifstream &names_list, string name)
{
string line;
while (getline(names_list, line))
{
if (line.find(name) != string::npos)
{
cout << line << endl;
}
}
cout << name << " not found" << endl;
}
Last edited on
Implement a loop and a counter.
Then
 
cout << "#" << num;

Put that before cin >> name
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Babyname(ifstream &names_list, string name)
{
string line;
int i = 0;
while (getline(names_list, line))
{
if (line.find(name) != string::npos)
{
cout << line << endl;
} 
cout << i << endl;
i ++;
}
cout << name << " not found" << endl;

}
Assuming the line number is separated from the name by a space:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Babyname(std::ifstream &names_list, std::string name)
{
    std::string line;
    bool found = true;
    while (!found && getline(names_list, line))
        found = line.find(name) != std::string::npos;

    if (found)
    {
        std::string num = line.substr(0, line.find(' '));
        std::cout << num << '\n';
    }
    else
    {
        std::cout << "I'm afraid that name wasn't very popular at all.\n";
    }
}


The two previous responders don't appear to have read your actual question.
Topic archived. No new replies allowed.