c++ifstream

Receiving numeric values and letters when reading text from file


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?


Solution

  • 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;
        }