I'm just starting to learn c++ and need to know how would you read the first line from a file and write to a new file? thanks

Did you perhaps try and could you show us your progress so far?

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

int main()
{
    ifstream in;
    in.open("file.dat");
    
    if(!in) 
    {
        cout << "Cannot open input file.\n";
        return 1;
    }
    
    
    char num[15];
    
    while(in) 
    {
        in.getline(num, 15);
        cout << num << endl;
    }
    
    in.close();
    return 0;
}

This is print out all the data in the file but I want it to read each line for the file and have it print to a new file..

well you need an ofstream object opened to the file that you want. after you do that in for loop output the char array to the file using the >> operator.

int main ()
{
    int getFirstLine;
    ifstream inFile;
    ofstream outFile;
    

    inFile.open("originalFile.dat");
    outFile.open("File1.dat");
    
    inFile >> getFirstLine;
    
    outFile << fixed << "Get First One:  " << setprecision(2) << getFirstLine <<endl;
    
    inFile.close();
    outFile.close();
}

basically, this revised code only write the first line to new file (File1.dat) from the original file. How do I get it to write 15 lines(because originalFile.dat contains 15 lines) to 15 different separate .dat files? I think I need to do an array or some sort but I can't figure it out. If anyone can help me.... thanks

You have to create the "file1.dat" filename each time through your loop. You need stringstream or sprintf or something similar to do that.

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.