1 Replies - 166 Views - Last Post: 09 October 2012 - 07:13 PM Rate Topic: -----

#1 mjmasopust  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-October 12

problem searching for a word in a string

Posted 09 October 2012 - 06:49 PM

I'm trying to make a program that will let you type in a name and then it will search a text file and after it is found it will put out the word and the line after into the screen. However after i get the name in and open the text file into a string I have no idea where to go from there. This is what i have so far
[
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    
    string n;
    string line;
    size_t find;
    std::cout << "** Name Popularity Program **\n";
    std::cout << "\n";
    std::cout << ">> Please enter a first name to search for:";
    std::cin  >> n; //only shows first letter
    std::cout << n << endl;
    ifstream file;
    file.open("/Users/mjmasopust/Desktop/HW9-PE1/firstnames-mac.txt");
    while (! file.eof())
    {
        getline(file, line);
        find = line.find(n);
    }
    
    return 0;
}

]

This post has been edited by jimblumberg: 09 October 2012 - 10:18 PM
Reason for edit:: Added missing Code Tags, Please learn to use them.


Is This A Good Question/Topic? 0
  • +

Replies To: problem searching for a word in a string

#2 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1074
  • View blog
  • Posts: 4,533
  • Joined: 09-June 09

Re: problem searching for a word in a string

Posted 09 October 2012 - 07:13 PM

Your reading the file line by line, why not put a counter in that loop. If the name is found, then output the line number and the word you found.

example
int line_num = 0;
while(getline(file, line))
{ 
   line_num++;
   find = line.find(n);
   if(/* if found */) 
      //output word and line number
}



To check if the line was found, look at what line.find returns if it fails.

here's a link to std::string::find documentation

http://www.cplusplus...ng/string/find/
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1