Receiving numeric values and letters when reading text from file

83 views Asked by At

When I try to read text from a file, I'm getting numeric values and letters in my output instead of just the text.

This is my GreenLang.cpp:

#include <iostream>
#include <string>
#include <fstream>

class ScanErrors {
protected:
    char* element;
    char codeElement;
    std::string path;
    std::string source;

public:
    ScanErrors (std::string filePath) {

        std::ifstream fileRead;
        fileRead.open(filePath);
        while (!fileRead.eof()) {
            fileRead.get(codeElement);
            scan(codeElement);
        }
        fileRead.close();
    }
    
    void scan(char code) {
        std::cout << code << std::endl;
        std::cout << std::to_string(code);
    }
};

int main() {
    ScanErrors scanner("code.gl");

    return 0;
}

This is my code.gl:

Hello, World!

My output:

H
72e
101l
108l
108o
111,
44
32W
87o
111r
114l
108d
100!
33!
33

Why do these numeric values appear instead and how can I get the text value?

2

There are 2 answers

0
Zubair Amin On BEST ANSWER

If you want to print only the characters and not their ASCII values, you can remove the line std::cout << std::to_string(code); from your scan function:

  void scan(char code) {
        std::cout << code << std::endl;
    }
0
Some programmer dude On

There's no overload of std::to_string that takes a char as argument.

It will instead be converted to an int, and you get the string representation of the numeric int value.

If you look at an ASCII table you will see that e.g. 72 is the numeric integer representation for the character 'H'.

If you want to get a string containing the character, then there is a std::string constructor overload that allows that:

std::cout << "String of only one single character: " << std::string(1, code) << '\n';