C++不会根据需要将数字/数字插入向量

C++ does not insert numbers/digits into the vector as desired

本文关键字:数字 插入 向量 C++      更新时间:2023-10-16

我正在编写代码,我的程序需要将变量和常量与给定的方程分开。这是我最初的想法:

std::string eq = argv[1];               // eg: y=2x+5
std::vector <char> variables;
std::vector <int> constants;
for(int i = 0; i < eq.size(); i++) {
  if(isalpha(eq[i]) && eq[i] != 'c') {
  variables.push_back(eq[i]);
  }
}
for(int i = 0; i < eq.size(); i++) {
  if(isdigit(eq[i])) {
  constants.push_back(eq[i]);
  }
}
for(auto j: constants) {
  std::cout << j << std::endl;
}

一切都很好,直到方程中的常数被分离并存储在向量constants中。每当执行代码并检查向量constants的内容时,都会返回完全不同的错误值。下面是一个示例:

等式:y=2x+5

所需输出(来自向量constants)= 2, 5

程序生成的输出 = 50, 53

知道我哪里出错了吗?编译期间未报告任何错误。

在 ASCII 字符集中,'0''9' 个字符的数值为 4857 。 将char转换为int将给出数值。 例如,值为 '4' 的字符的数值为 52 。 这解释了你的值"如50、53或52"。

要将数字转换为您期望的值('0'转换为0,.... '9' 9 ) 减去'0' 。 例如;

 char x = '5';
 int n = x;
 int v = x - '0';
 std::cout << "'" << v << "' has the numeric value " << n << 'n';

请注意,不同的(非 ASCII)字符集将给出不同的数值。 但这种类型的转换适用于所有标准字符集。