New to C++ and ran into another hurdle to learn from. Trying to make a simple program that reads from a file and stores the characters into a char array.
#include <iostream> #include <fstream> #include <string> #include <cctype> using namespace std; int main () { const int SIZE = 9; char arr[SIZE]; char currentChar; int numChar = 0; int i = 0; ifstream infile ("file.txt"); if (!infile) { cout << "Can not open the input file" << " This program will end."<< "\n"; return 1; } while(infile.get(arr[i])) { i++; numChar ++; } for(i=0;i<numChar;i++) { cout << arr[i]; } cout << "\n" << arr[1]; return 0; } Contents of file.txt:
A a 9 ! Problem is that:
for(i=0;i<numChar;i++) { cout << arr[i]; } Has output that is identical from the file read, but when I manually checked the array elements. arr[1] is storing a white space and arr[3] ='a'. I found this out when I was trying to evaluate what type of char each element was with isalpha and isdigit statements. Why is it storing 2 elements of whitespace before getting to the next line and why does the output look correct though it actually isn't? Is there a much simpler and more efficient way to this than what I'm doing?
Thank you in advance for your help.
newlineand alinefeedcharacter before moving on to the new line.newline, so don't get any ideas about skipping two spaces (unless you could care less about running on linux, in which case you can do what ever you want)