문제

I have a dynamically allocated memory:

//dynamic buffer
char *mybuffer;
cin>>n;
mybuffer=new char[n];
//open file for reading
ifstream inpt(filename.c_str(), ios::binary);
for(unsigned int i=0;i<n;i++){

    //copy every single character into buffer
    inpt.read(mybuffer[i],1);
}

says error, argument of type char is incompatible with type char*

I need to read the files character by character and store in buffer. Note that this is sample code. I actually should read multiple files and store in single buffer so I should use buffer with index.

How can I improve this code?

도움이 되었습니까?

해결책

The error

error, argument of type char is incompatible with type char*

is due to istream::read takes pointer to char:

istream& read (char* s, streamsize n);

so you should write:

inpt.read( &mybuffer[i], 1);

다른 팁

You should pass a pointer to char as input of ifstream::read, but you're passing a char.

inpt.read(&mybuffer[i],1);
          ^

I would suggest you to avoid allocating memory and pass to read.Here is the sample code which opens a file and reads each line into the "std::string" object and prints on the console. "std::string" would take care of all memory management and you can read it and use in your program.

int main() 
{

std::string  file =  "input.txt";
std::string line;
std::ifstream  text_filestream(file.c_str());

while(std::getline(text_filestream, line)) {
 // now you can use the line object by anyway as per your requirement.
 std::cout<<line<<std::endl;
 }
}  

I guess this improvement should be done in your program.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top