Jump to content

simple file read error - help.

Go to solution Solved by fizzlesticks,

When using .get to fill a char array it only reads n-1 characters then adds a '\0' to the end for the last character. 

 

http://www.cplusplus.com/reference/istream/istream/get/

It is the first time i have encountered with this problem, that when i read a number from a text file and then have specified length of characters to read afterwards, it cuts of one of the characters.

text file sample:

3 forwhomthebelltollsa
-6 verycomplexnumberrrr

Program:

int n;
    int f,s;
    string fi,se;
    char fir[50],sec[50]; // 50 because i need some space after read 20

    ifstream fd("file.txt");
   // fd>>n; 
   // cout<<n<<endl;
    fd>>f;
    cout<<f;
    fd.ignore(1,' '); //first thing after getting one char short i put this but it only eliminated the whitespace before chars
    fd.get(fir,20);// should read: "forwhomthebelltollsa"
    cout<<" "<< fir;// prints: "forwhomthebelltolls"

 

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to comment
https://linustechtips.com/topic/548414-simple-file-read-error-help/
Share on other sites

Link to post
Share on other sites

Just now, fizzlesticks said:

When using .get to fill a char array it only reads n-1 characters then adds a '\0' to the end for the last character. 

 

http://www.cplusplus.com/reference/istream/istream/get/

We have been using this in school without knowing this.. great job teacher

i5-4690k, R9 380 4gb, 8gb-1600MHz ram, corsair vs 550w, astrock h97m anniversary.

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×