mrbw
mrbw

Reputation: 39

Char array outputting correctly but not actually storing right values

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.

Upvotes: 2

Views: 119

Answers (1)

Biruk Abebe
Biruk Abebe

Reputation: 2233

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
..

Upvotes: 2

Related Questions