This function reads a text file containing numbers of char size(the text file is written in char in another program) and I need to get them into integers after reading. Since the rest of my program is in C++, I want to get this function in C++ too. The most trouble I have is with the fread sizeof(char)
void VAD_Selector(vector<int>& x){
FILE *ptr = NULL;
if ((ptr = fopen(USABLE_VAD, "r")) == NULL) {
cout << "Error opening VAD file" << endl;
exit(0);
}
short mode = 0;
char VAD_input[2] = "0";
x[0] = 0;
int i = 1;
while (fread(VAD_input, sizeof(char), 1, ptr)) {
mode = (short)atoi(VAD_input);
if (mode != 1)
x[i] = 0;
i++;
}
fclose(ptr);
}
this is what the input text file look like:
00000000000000000000000000000000000001111111111111111111111111111111111111111111111
there is not output but what I want to do is get all data from text file into th x vector (x[0] is always 0)
this is what I tried:
ifstream ptr;
ptr.open(USABLE_VAD);
if (!ptr.is_open()) {
cout << "Error opening VAD file" << endl;
exit(0);
}
else {
x[0] = 0;
int i = 1;
char c[2] = "0";
while (!ptr.eof()) {
ptr >> c;
x[i] = atoi(c);
cout << x[i];
i++;
}
}
ptr.close();
I get this error in VS2015 before ptr << c
:
Exception thrown at 0x60C4B8BA (msvcp140d.dll) in Algo_gen.exe: 0xC0000005: Access violation reading location 0x6CB95C28.
If there is a handler for this exception, the program may be safely continued.
I changed the while loop condition and used c - '0'
and it works. Thanks to everybody. If it can help anybody else, there is my solution:
void VAD_Selector(vector<int>& x){
ifstream ptr;
ptr.open(USABLE_VAD);
if (!ptr.is_open()) {
cout << "Error opening VAD file" << endl;
exit(0);
}
else {
x[0] = 0;
int i = 1;
char c = '0';
while (ptr >> c) {
x[i] = c - '0';
i++;
}
}
ptr.close();
}