Reading char from File to Array

Hello,

I'm trying to read a series of char letters (one per line) from a file and into an array. For some reason, instead of reading the letters, it's just reading/showing "Ì".

Here's what I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
   ifstream inputFile;
   ofstream outputFile;

   const int Array_Size = 20;
   int count = 0;
   char CorrectAnswers[Array_Size];

   inputFile.open("CorrectAnswers.txt");

   while (count < Array_Size)
   {
      inputFile >> CorrectAnswers[count];
         count++;
   }

   for (int countr = 0; countr < Array_Size; countr++)
   {
      cout << CorrectAnswers[countr] << endl;
   }

   return 0;
}


The file "CorrectAnswers" contains 20 letters, one character per line. The compiler does not display any errors, but, as stated before, everything comes out as "Ì" on the console as well as the output file.


Any helps/pointers will be appreciated!

Oh and yes, this only happens for char. If I used a different file with only numbers, and declare the array as an int, it works perfectly and displays the numbers.
1
2
3
4
5
6
7
char singleCharacter;
while ( count < Array_Size && !(inputFile.eof()) )
  {
       inFile.get(singleCharacter);
       CorrectAnswers[count] = singleCharacter;
       count++;
  }
No luck, unfortunately, I'm still getting the same output.
remember to close the file after reading in the info. Also try putting in the full path to the file just to make sure your compiler is looking in the right place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// print the content of a text file.
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream ifs;

  ifs.open ("test.txt", std::ifstream::in);

  char c = ifs.get();

  while (ifs.good()) {
    std::cout << c;
    c = ifs.get();
  }

  ifs.close();

  return 0;
}
and by the way, your above code from the first example works fine for me.
Although it tries to print out more of the array even if only part of it is full...the last characters come out something strange. But your code compiles and runs with a text file of characters in the same folder.
So, I had it checked out by one of our TA's. It turns out that something was wrong with the file themselves.

What was wrong with the file? We don't know. But I'm assuming there was an error in reading the file. The above code worked when we started everything from scratch (program as well as creating new original files).


Thanks for the assistance, everyone!
Last edited on
Topic archived. No new replies allowed.