从文件读取文本时接收数值和字母

问题描述 投票:0回答:2

当我尝试从文件中读取文本时,我在输出中获取数值和字母,而不仅仅是文本。

这是我的

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

这是我的代码.gl:

Hello, World!

我的输出:

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

为什么会出现这些数值以及如何获取文本值?

c++ ifstream
2个回答
4
投票

std::to_string
不存在以
char
作为参数的重载。

它将被转换为

int
,并且您将获得 numeric
int
值的字符串表示形式。

如果您查看ASCII 表,您会看到例如

72
是字符
'H'
的数字整数表示。

如果您想获取包含该字符的字符串,那么有一个

std::string
构造函数重载 可以实现:

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

1
投票

如果您只想打印字符而不打印它们的 ASCII 值,您可以从扫描功能中删除行

std::cout << std::to_string(code);

  void scan(char code) {
        std::cout << code << std::endl;
    }
© www.soinside.com 2019 - 2024. All rights reserved.