Deckdyl
Deckdyl

Reputation: 103

How do I read a segment of a file, defined by the number of characters to read, in C++?

I have some problems reading specific data from a file. The file has 80 characters on the first and second line and an unknown number of characters on the third line. The following is my code:

int main(){
    ifstream myfile;
    char strings[80];
    myfile.open("test.txt");
    /*reads first line of file into strings*/
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    cout << "Handphone: " << strings << endl;
}

How do i do the actions in the comments?

Upvotes: 2

Views: 446

Answers (2)

StackHeapCollision
StackHeapCollision

Reputation: 1813

In your case it will be more appropriate to use string rather than char[].

#include <string>
using namespace std;

int main(){
    ifstream myfile;
    //char strings[80];
    string strings;
    myfile.open("test.txt");

    /*reads first line of file into strings*/
    getline(myfile, strings);
    cout << "Name: " << strings << endl;
    /*reads second line of file into strings*/
    getline(myfile, strings);
    cout << "Address: " << strings << endl;
    /*reads third line of file into strings*/
    getline(myfile, strings);
    cout << "Handphone: " << strings << endl;
}

Upvotes: 1

Alex
Alex

Reputation: 7838

char strings[80] can only hold 79 characters. Make it char strings[81]. You can forget about the size altogether if you use std::string.

You can read lines with the std::getline function.

#include <string>

std::string strings;

/*reads first line of file into strings*/
std::getline( myfile, strings );

/*reads second line of file into strings*/
std::getline( myfile, strings );

/*reads third line of file into strings*/
std::getline( myfile, strings );

The code above ignores the information that the first and second lines are 80 chars long (I'm assuming you're reading a line-based file format). You can add an additional check for that if it's important.

Upvotes: 3

Related Questions