0

Hello, I am new to C++ and very lost. I have attempted this program but my output displays file was unable to open. I am not sure I am even on the right track. Here is my project:

Write a program that reads strings from a file into a vector. Ask a user to enter a string to be found. The program should display the index in the vector where that string was foud and the string, or display a messag telling teh user that the string was not found.

Any help would be appreciated!!
Here's what I have so far:

#include <vector>
#include <fstream>
#include <conio.h>
#include <iostream>
using namespace std;

int main()
{
    vector<string> names;
    string aName = "";//means empty
    
    ifstream file;
    
    file.open("names2.txt");
    
    if( file.fail() )
    {
        cout << "File failed to open.";
        getch();
        return 1;
     }
  
        while( getline(file,aName) )//use comma its 2 perameters
        {
               names.push_back(aName);
        }
        
  file.close();
  
  for(int i=0; i<names.size(); i++)
  cout << i << " " << names[i] << endl;
  
  getch();
  return 0;
}
2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by jenbrandau341
0

On the right track!! The program is reading the file and displaying all the names with index correctly but you need to include string header file.

Now for your question, ask the user to enter a string and then start comparing it from the start of vector. Something like..

int i;
for(i=0; i< (int)names.size(); i++)
{
    if(strcmp(usrInput, names[i]) == 0)
         break;
}

Edited by vidit_X: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.