从文件中读取数字并将它们存储为十进制而不是 C++ 中的 ASCII

Reading digits from a file and storing them as decimal instead of ASCII in C++

我正在尝试从存储在文本文件中的数字中读取单个数字。我有以下内容:

int main() {
  int test;
  std::ifstream inFile("testNum.txt");
  test = inFile.get();
  std::cout << test  << std::endl;
}

testNum 中的数字看起来像 95496993,我只想一次读取一个数字。

当打印出 "test" 变量时,我得到数字 57,它实际上是数字 9 的 ASCII 码。

如何读取文件以存储实际数字而不是 ASCII 值?

我也尝试过使用 int a = int(test) 转换为 int,但这没有用。 . 我的最终目标是能够单独读取数字的每个数字并将它们分别存储在某个地方。

谢谢。

尝试使用:

char test;

或者:

std::cout << (char)test << std::endl;

std::cout 数据编码取决于您要输出的元素类型。

在这种情况下,您希望将“9”输出为 ASCII 数字,而不是 57 作为其整数表示形式(char 与 int)。

将 ASCII 数字转换为 int 的典型 C 方法是使用

test=in.GetFile()-'0' // or use 48 instead of '0'

那样的话,您最终会得到数字 9 作为 test 的值,而不是 57。