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;
}

Recommended Answers

All 2 Replies

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;
}

Thak you so much for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.