2

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.

6
  • Because on windows each line ends with a newline and a linefeed character before moving on to the new line. Commented Apr 16, 2016 at 21:35
  • If you are on a different platform (say linux) it would only end in a 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) Commented Apr 16, 2016 at 21:37
  • There are newline characters after each line. Commented Apr 16, 2016 at 21:37
  • I'm actually on ubuntu 15.10. I kind of understand, correct me if i'm wrong. Because i'm reading to end of file instead of to each endline its putting them into the array. Syntax wise how could I change the while statement that reads the array so that when arr[i] = "\n" or some such thing that it ignores that and moves on and stores the array correctly? Commented Apr 16, 2016 at 21:59
  • @mrbw I don't know if you can actually do this, but the simplest solution would be to make all of the characters in the file on the same line. Commented Apr 16, 2016 at 22:21

1 Answer 1

2

What you are reading is a new line character next to each character in your file. if you cast the characters to int when you display them you get something like:

65 //ascii code for 'A' at arr[0] 10 //ascii code for new line character(\n) at arr[1] 97 //ascii code for 'a' at arr[2] 10 .. 
Sign up to request clarification or add additional context in comments.

1 Comment

New Line is a white space.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.