Home > Back-end >  How to extract a perticular line from an external txt file using C and then output the line as a s
How to extract a perticular line from an external txt file using C and then output the line as a s

Time:11-21

This code only works for printing the first line only. What should I do to print only the second or third line?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
    string str;
    string lineFromFile;
    ifstream myfile("./file.txt");
    while(getline(myfile,lineFromFile)){
    str = lineFromFile;
    cout << str << endl;
    break;}
}

CodePudding user response:

You can count the lines and equate your expected line number with the counter to output your line as in the below example.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main(){

int count = 1; 
int line_count; 

string str;
string lineFromFile;
ifstream myfile("./file.txt");

std::cin >> line_count; 

while(getline(myfile,lineFromFile)){
    if(line_count == count)
        {
            str = lineFromFile;
            std::cout << str << std::endl; 
            break; 
        }
count  ; 
    }


}
  • Related