Next, I am trying to read individual integers from a file to an array. The book[1] I have says get(): "Returns the next character extracted from the input stream as an int." So, I suspected it to work when considering integers.
I have read many "suggestions," including "stringstream" which I believe to be overkill if get() is supposed to return an integer. Although I have read many suggestions, nothing has worked. For this reason, I am posting my code. I am a beginner.
In my file, I have 12345678910. What I currently get back when I run the below code is:
239
187
191
49
50
51
52
53
54
55
56
57
49
48
-1
References:
[1] Bronson, Gary J.. C++ for Engineers and Scientists (Page 480). Cengage Textbook. Kindle Edition.
You read a character but store it as an int. The digit 1 has the ascii code 49 so your array will store 49 as an int.
To convert your character to an int use series[i] = inFile.get() - '0';
That did change part of my output to 12345678910, but I still get:
191
139
143
1
2
3
4
5
6
7
8
9
1
0
-49
and I only have 12345678910 in my text file. You have any idea why? I know that there could be hidden characters that get() is picking up. Is that the case? If so, how can I filter them? should I use an "if". I would rather read a clean input. I know getline() reads differently than get() but I don't need a string, I need integers.
I changed my code to use atoi(). I am still getting odd output: large negative numbers, symbols, a zero in between my desired integer, and my desired integers-12345678910.
I need to get rid of the large negative numbers, symbols, and zeros. I can, if I have to, filter all large negative numbers to the top (I have done this with a vector recently and figured it out on my own! :) ). I don't want my code to be so bloated, and I would still have the problems with the symbols. I have to be doing something wrong but I have no idea what I am doing wrong. Here is the new code.
Thanks. I discovered that some of the negative numbers and the symbols were characters in the text file. I used your original suggestion which is so simple. I thank you greatly.