C++ file handling -


i have 2 text files "source1" , "source2" contain integers 3 4 1 2 56 , 2 45 34 23 45 respectively.

displaying them on screen.

even though there not error given sure array isn't getting correct data files source1 , source2.

the ouput should integers in file it's not expected.

the ouput should integers int file it's not expected.

i guess there problem read , write.

 #include<stdio.h>  #include<fstream>  #include<iostream>  using namespace std;    int main() {      fstream file1;      fstream file2;      file1.open("source1.txt");      file2.open("source2.txt");      int source1[20];      int source2[20];      file1.read((char*)&source1,sizeof(source1));      cout<<source1<<"\n";      file2.read((char*)&source2,sizeof(source2));      cout<<source2<<"\n"; } 

here issues noticed program.

reading arrays

your code reads in 20 integers, whether there 20 or not. if file contains 4 binary integers, how handle error?

your file ends .txt extension, assume data in human readable (text) format. read method not translate "123" number 123. read method save mirror of data, is.

arrays , cout

the c++ programming language's cout not have facilities printing arrays of integers. you'll have use loop print them. also, should use separator between integers, such tab, newline, comma or space.

binary & text writing

if want write internal representation of number, use ostream::write. if want use formatted or textual representation use operator>>.
if integer more byte wide need know if platform outputs highest byte first (big endian) or last (little endian). makes big difference when read values back.

use vectors not arrays

vectors easier pass , take care of dynamic growth. arrays fixed capacity definition , require 3 parameters when passing: array, capacity, , quantity of items in array. std::vector, vector needs passed because other information can obtained calling vector methods, such vector::size().


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -