I want to read characters(256 of them) from a file and put thier numeric value in an array.Then i want to send 16 characters in batches from the array onto a loop in successive steps to perform operations on them.

My problem:

First i can read the first batch of 16 characters easily. But after the second or third it starts showing 0,32 or 255 as the characters,but there are no spaces and it does not read the character but just fills it with blanks.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>


using namespace std;


                  
int main()
{
    
    
   int size=0;
   int ff=0,ww=0,g=0,h=0,l=0;
   
   char cc[256];
   int a[256];


   ifstream infile;
   ofstream myfile;
   infile.open("as86.txt",ios::binary);

  infile.get(cc,257);  
  infile.close();  
  }
  
  cout <<< endl;

do

{

    h=g+16;

    
    for(int i=g;i<h;i++){
  a[i] =  (unsigned char)cc[i];
  cout << a[i] << "  ";
  }

g=h;
l++;

}

while(l<=15);

Now unfortuantely it only prints about thew first 32-35 characters properly,after that it goes haywire.

What's wrong ? Any better ways to read character from file and send thier numeric value into an array.

Thanks.

Recommended Answers

All 3 Replies

Part of the problem is you are trying to read a text file in binary mode. In binary mode you need to use read() to get a block of bytes. I can see how it might read some of the chars in that way but there must be some subtlety that is goofing it up. I would omit the ios::binary and see if that improves things.

Also, why are you trying to read 257 characters into the 256 char array? (that would be valid if you had indexes 0 through 256 but you only have up to 255)

Jonsca,I love you!!!!

This problem has been bugging me for weeks.Thanks a million.

I didn't know i had to use read instead of get.

Anyway when i take off the binary mode it starts displaying a 0 in between every other numeric value,so i've let it as it is.And also the (CC,17) thing bugged me,but when i change it to (CC,16) it only reads 15 characters.

Thanks a lot sir.

Also, why are you trying to read 257 characters into the 256 char array? (that would be valid if you had indexes 0 through 256 but you only have up to 255)

A brief mea culpa: You are partially right. The get() function leaves room for the terminating null, so only gets n-1 characters, but your array has to be that size n as well. That's why you were getting 15 chars you need an array that holds 17 chars to get 16.

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.