Ok i have a file of names that looks like this:

john
mary
joe
matthew

im trying to use a for loop to store each name in a variable or string so i can use a for loop again later to output each name

im pretty new to c++ and i cant figure this out

i can only figure out how to read 1 line from a file


thanks in advanced to anyone that helps :P

Try using a while look for the first loop instead. A for loop implies you know how many times you need to go through the loop. A while implies you exit the loop when some criteria is satisfied, such as you reached the end-of-file ( EOF ).

Since you seem to know code tags, you should be aware that for really good help you need to post your code... :icon_wink:

Well. Regardless of the loop kind (assuming it's allowed to iterate enough times), it should read in the info:

while ( in >> word )
  std::cout<< word;

Where in is your input file stream and word is something used to store the information of the file.

well here is the code i have

int main()
{
    char name[20];
    
    ifstream infile;
    
    infile.open("names.txt", ios::in);
    
    if (infile)
    {
    
        infile.get(name, 20);     
        
    }
    else
        cout << "Error Opening File" << endl;
    infile.close();
        
   return 0;
   
}

Im trying to put the name on each line into a separate array so after i could do something along the lines of

while (i != 0){
cout << "Name: " <<  name[i] << endl;
i++;
}

you will need an array of strings. There's a couple ways to do it

// this array will hold up to 100 names and each name can be up to 19 characters long.
char names[100][20];

// This is a c++ array that can contain an unlimited (almost) number of names
// and each name can be unlimited (almost) length
vector<string> names;
This article has been dead for over six months. Start a new discussion instead.