Click here to Skip to main content
15,356,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if there are 10 names (each line separated). How can I access any specific name on specific line.
I tried changing string to array but it prints single digit instead complete name.

What I have tried:

string f;
fstream file;
file.open("names.txt");
for (int i = 0; i < 10; i++)
{
    file>>f;
    cout<<f<<endl;
}


Content of names.txt

Hamza   
usama
ali
saleem
sharif
haseeb
saeed
sadiq
usman
bilal
Posted
Updated 21-May-22 1:30am
v2
Comments
Richard MacCutchan 21-May-22 7:10am
   
You have not shown the contents of your "names.txt" file. Also do not write a loop that way, as there may be more or less than ten items in the file. Use a test for end-of-stream to terminate the loop.
Hamza Jameel 21-May-22 7:16am
   
I have updated question with "names.txt" content.

You need to read the file one line at a time (to separate the names) and then select the specific line you need, probably by the line number which you can work out by keeping a count you update as you read each line.

You can do this with getline (string) - C++ Reference[^]
   
Try this:
C++
fstream file;
file.open("names.txt");
char line[64];
int lineno = 1;
do
{
    file.getline(line, 64);
    if (file.gcount() > 1 && !file.fail())
        cout << lineno << ". " << line << endl;
    lineno++;
} while(!file.eof());
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900