控制台输出显示ASCII值,而不是数字的预期数字

Console output displays ASCII values instead of expected digits of a number

本文关键字:数字 显示 输出 ASCII 控制台      更新时间:2023-10-16

我面临着在C 中打印两个大整数数字的单个数字的问题。这些数字的长度高达600位,我正在尝试使用字符串和向量来存储和操纵它们。但是,当我尝试循环浏览向量并打印数字时,我会得到意外的结果 - 数字的ASCII值正在控制台上显示。我正在寻求有关如何解决此问题的指导。

这是我遇到的问题的示例:

对于第一个字符串,我输入数字9 8 7 6 5 4 3 2 1,但是在控制台上,我得到以下结果:

[0]57
[1]56
[2]55
[3]54
[4]53
[5]52
[6]51
[7]50
[8]49
#include <iostream>
#include <vector>
std::string Sum_Of_Two_Long_Integers()
{
  std::string First_String;
  std::string Second_String;
  std::string Result_String;
  std::cout << "Please enter the first number: ";
  std::getline(std::cin, First_String);
  std::cout << "Please enter the second number: ";
  std::getline(std::cin, Second_String);
  std::vector<int> First_String_Vector(First_String.length());
  std::vector<int> Second_String_Vector(Second_String.length());
  for (int Counter = 0; Counter < First_String_Vector.size(); ++Counter)
  {
    First_String_Vector[Counter] = First_String[Counter] - '0'; // Convert char to integer
    Second_String_Vector[Counter] = Second_String[Counter] - '0'; // Convert char to integer
    std::cout << "[" << Counter << "]" << First_String_Vector[Counter] << std::endl;
  }
  return Result_String;
}
int main()
{
  std::string Result_String = Sum_Of_Two_Long_Integers();
  std::cout << "Result = " << Result_String << std::endl;
  return 0;
}

我相信这个问题可能与我如何处理角色的ASCII值有关。有人可以帮助我了解如何在不遇到ASCII表示的情况下正确提取和打印单个数字吗?

First_String_Vector[Counter] = First_String[Counter] ;
Second_String_Vector[Counter] = Second_String[Counter] ;

数字在您的字符串中存储为ASCII,在将它们放入向量之前,应转换为整数。

这将有能力:

First_String_Vector[Counter] = First_String[Counter] - '0';
Second_String_Vector[Counter] = Second_String[Counter] - '0';

我还会在填充向量之前添加一张有效输入的支票,以确保您仅读取数字:

if(First_String[Counter] < '0' || First_String[Counter] > '9' ||
   Second_String[Counter] < '0' || Second_String[Counter] > '9')
{
    std::cout << "Invalid inputn";
    return "":// Or better throw an exception
}

编辑: '6'不等于6。第一个是char,其值为字符" 6"的ASCII,第二个是整数6。

ascii是一个编码。字符被映射到一些数字。" 0"的值48,'1'is 49,...,'9'is 57

更精确的C 不能保证使用ASCII编码(尽管我不知道不使用它的实现(,但它确实保证了" 0" ...'9'具有连续的整数值。因此'6' - '0'将为我们提供整数6。