#include <iostream>
#include <fstream>
#include <cstdlib>
usingnamespace std;
constint NUMBERS = 26;
ifstream infile;
ofstream outfile;
void read(int first_array[], int second_array[], int sum_array[])
{
int i = 0, k = 0, convert = 0;
char check;
infile.open("MyNumbers.txt");
if (!infile)
{
cout << "Failed to open data file!\n";
cin.get();
exit(0);
}
while (infile.get(check))
{
if (check != '\n')
{
convert = check - '0';
first_array[i] = convert;
i++;
}
else
{
break;
}
}
for (int j = 0; j < NUMBERS; j++)
{
cout << "First array: " << first_array[j] << endl;
}
infile.close();
}
int main()
{
int first_line[NUMBERS] = {0}, second_line[NUMBERS] = {0}, sum_line[NUMBERS] = {0};
read(first_line, second_line, sum_line);
// cin.get();
return 0;
}
The code is suppose to read in the first number (number 7) into the program and store it in the first_array (after converting it to an integer 7 by subtracting the character '0'). Then, the next character collected from infile.get() should be the newline \n character. But, when I run it in my terminal, it has a -35 in the second position. I don't know why it is getting a -35 in the second position because it is suppose to skip to break if a newline is encountered. If I use the integer 13, it seems to work out properly, but I really want to use the \n newline character. Can anyone help me with this?
I assume you are using Windows, but I don't know which compiler.
In a text file on Windows, line breaks are usually represented by a pair of characters, the CR-LF (carriage-return, line-feed). These have the decimal values of 13 and 10, or in C++, '\r' and '\n'.
When a file is opened in text mode, you can normally consider just the '\n' as there is some automatic transformation going on. But if the file is opened in binary mode, you will get to see exactly what is in the file, with no translation.
Now I tested your code, and the only way I can reproduce your result is by changing line 16 to infile.open("input.txt", ios::binary); because the default is to open in text mode. It seems somehow you have the file open in binary mode.
A suggested workaround is to change line 27 to if (check != '\n' && check != '\r')
hmm... it seems to me that your numbers are too great for a "int" (on gcc, if I remember well, an int is 2bytes long, so - seeing it is "signed" - it should be able to manage values up to a value around 35,000)... the memory limit for "int" however depends from compiler to compiler (while "short", "long" and "char" usually have the same size for all compilers.... if I remember well: short = 2bytes; long = 4bytes)