Closed. This question needs debugging details。它当前不接受答案。












想改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。

4年前关闭。



Improve this question




我正在编写代码,程序需要将给定方程式中的变量和常量分开。这是我想到的最初想法:
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;
}

一切都很好,直到方程中的常量被分离并存储在 vector constants中为止。每当执行代码并检查 vector constants的内容时,都会返回完全不同且不正确的值。这是一个例子:

等式:y = 2x + 5

必需的输出(来自constants vector )= 2,5

程序生成的输出= 50、53

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

最佳答案

在ASCII字符集中,字符'0''9'具有从4857的数值。将char转换为int可得到数值。例如,值为'4'的char的数字值为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)字符集将提供不同的数值。但是,这种类型的转换适用于所有标准字符集。

关于c++ - C++不会根据需要在 vector 中插入数字/数字。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35668255/

10-11 22:33
查看更多