Posting a data file from cat to a C ++ program

I am looking for some help that links a file (16-bit signed small trailing integers) from the command line to my program:

cat data.dat | myprogram 

Then it must convert the data to 16-bit integers. It works for the first 12 values. The 13th value is incorrect, followed by zeros.

The second problem is that the program seems to enter the while loop only once.

I am using Windows + MinGW.

My code is:

 #include <iostream> using namespace std; #define DEFAULT_BUF_LENGTH (16 * 16384) int main(int argc, char* argv[]) { char buf[DEFAULT_BUF_LENGTH]; while(cin >> buf) { int16_t* data = (int16_t*) buf; //to int for(int i=0;i<18;i++) { cout << data[i] << endl; } } return 0; } 

Output:

 0 9621 -14633 -264 5565 -12288 9527 -7109 11710 6351 4096 -5033 5773 147 0 0 0 0 

Thank you for your help!

+5
source share
2 answers

You can try using read() instead of the >> operator, which is usually used for formatted input. It is also useful to check how much data has actually been read:

 #include <iostream> using namespace std; #define DEFAULT_BUF_LENGTH (16 * 16384) int main(int argc, char* argv[]) { char buf[DEFAULT_BUF_LENGTH]; for(;;) { cin.read(buf, sizeof(buf)); int size = cin.gcount(); if (size == 0) break; int16_t* data = (int16_t*) buf; //to int for(int i=0;i<size/sizeof(int16_t);i++) { cout << hex << data[i] << endl; } } return 0; } 
+4
source

The cin >> buf statement does not populate all buf data. It reads only the following "set" of characters without spaces. Change cin >> buf to read(0, buf, sizeof(buf)) > 0

If you insist on using C ++ threads, change the start of your loop to:

 while (!cin.eof()) { cin.read(buf, sizeof(buf)); [...] 
+1
source

All Articles