Hi everyone, big time c++ newbie here, in fact I don't know too much at all about what I'm doing. But what I am trying to do at this point is read into a file created by my program, check and see if a name to be inputed is exists or not, and if not it is to be added to the list.

Here's what I've come up with so far...

vector<string> Names;
	
		ofstream ScoreFile;
		          do
		{
			 string PlayerName = GetLine( "Enter your name -->" );
			ScoreFile.open( "Scores.txt" );
			for ( vector<string>::size_type Index = 0
                                ; Index < PlayerName.size() 
                                ; ++Index )
				if  ( PlayerName == Names[Index] )
			ScoreFile << PlayerName;
			if ( ScoreFile ) break;
			ScoreFile.clear();
			cout << "File didn't open."  << endl;
		} while (true);

It does compile, but when I type in a name all hell breaks loose and it says vector subscript is out of range.

>; Index < PlayerName.size()
That doesn't make sense at all. You're using the length of the name entered to specify how many names are in the vector? Try Names.size() instead of PlayerName.size() .

>if ( PlayerName == Names[Index] )
Currently this fails because Index specifies an element that doesn't exist. Your vector is currently empty.

Compare and contrast:

std::vector<std::string> names;
std::ofstream out ( "Scores.txt" );

// Always check that your files are opened successfully
if ( out ) {
  while ( true ) {
    std::string name = GetLine ( "Enter your name -->" );

    // Assuming GetLine returns an empty string on failure
    if ( name.size() == 0 )
      break;

    std::vector<std::string>::size_type i;

    // Search for the name in our vector
    for ( i = 0; i < names.size(); i++ ) {
      if ( names[i] == name )
        break;
    }

    // If we didn't reach the end, the name exists
    if ( i == names.size() ) {
      names.push_back ( name );
      out<< name;
    }
  }
}

Okay. I fixed the for loop and added the second if statement you have shown me, but Scores.txt has nothing added to it after I run the program.

This article has been dead for over six months. Start a new discussion instead.