tags:

views:

400

answers:

2

I am learning C++ for the first time. I have no previous programming background.

In the book I have I saw this example.

#include <iostream>

using::cout;
using::endl;

int main()
{
    int x = 5;
    char y = char(x);

    cout << x << endl;
    cout << y << endl;

    return 0;
}

The example makes sense: print an integer and the ASCII representation of it.

Now, I created a text file with these values.

48
49
50
51
55
56
75

I am writing a program to read this text file -- "theFile.txt" -- and want to convert these numbers to the ASCII value.

Here is the code I wrote.

#include <iostream>
#include <fstream>

using std::cout;
using std::endl;
using std::ifstream;

int main()
{
    ifstream thestream;
    thestream.open("theFile.txt");

    char thecharacter;  

    while (thestream.get(thecharacter))
    {
        int theinteger = int(thecharacter);
        char thechar = char(theinteger);
        cout << theinteger << "\t" << thechar << endl;
    }


    system ("PAUSE");
    return 0;
}

This is my understanding about the second program shown.

  • The compiler does not know the exact data type that is contained in "theFile.txt". As a result, I need to specify it so I choose to read the data as a char.
  • I read the each digit in the file as a char and converted it to an integer value and stored it in "theinteger".
  • Since I have an integer in "theinteger" I want to print it out as a character but char thechar = char(theinteger); does not work as intended.

What am I doing incorrect?

+2  A: 

You are reading one char at a time from the file. Hence, if your file contains:

2424

You will first read the char "2" from the file, convert it to an int, and then back to a char, which will print "2" on cout. Next round will print "4", and so on.

If you want to read the numbers as full numbers, you need to do something like:

int theinteger;
thestream >> theinteger;
cout << char(theinteger) << endl;
Håvard S
Oh, I get it. A (char)acter is a single. Oh my for my dumb mistake.
newbie
+6  A: 

You are reading char by char, but you really (I think) want to read each sequence of digits as an integer. Change your loop to:

int theinteger; 
while (thestream >> theinteger )
{
    char thechar = char(theinteger);
    cout << thechar << endl;
}

+1 For a very nicely formatted & expressed first question, BTW!

anon
Yes, you are correct, Neil. I want to read each number as completely. Each number is on its own line. Is it common to make oversights like this as in you intend to do something but you use the incorrect commands? I hope that makes sense.
newbie