控制台输出显示ASCII值,而不是数字的预期数字
Console output displays ASCII values instead of expected digits of a number
我面临着在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。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在 txt 文件中显示前两个数字的程序
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么 sf::Text 显示点而不是数字?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 未来值公式显示疯狂巨大数字的输出
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 无法在C++中显示反转的数字
- 如何执行此程序,将键入的数字显示为数字值的多次
- Cpp代码故障(显示意外数字)
- 如何让我的代码显示文件名不正确或文件中数字的平均值?
- 为什么C++显示错误的数字?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- C++编译器只显示数字,不显示正确的输出
- 输入的数字与代码显示的数字不同,在结构中使用数组,为什么?
- 如何计算和显示C++中5个数字的平均值?
- 以8位数字形式输入日期并以英文形式显示
- 为什么我的 rand() 数字显示为 0