C++不会根据需要将数字/数字插入向量
C++ does not insert numbers/digits into the vector as desired
我正在编写代码,我的程序需要将变量和常量与给定的方程分开。这是我最初的想法:
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'
个字符的数值为 48
到 57
。 将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)字符集将给出不同的数值。 但这种类型的转换适用于所有标准字符集。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 在数字之间插入 + 或 - 符号以使其等于整数
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- 如何按数字顺序插入链表节点?
- 在 std::unordered_set <double>中插入多个非数字
- 在每个偶数特定数字之后,插入向量中
- 将可被数字整除的数字插入到向量中
- 将数字有序地插入链接列表中
- 使用模板的插入函数会丢失数字
- 如何将文件中的数字插入到链表中
- 如何只插入数字和字母应该显示消息或其他内容
- 无法在二维矢量中插入数字
- 无法将数字插入到基于 char16_t 的自定义C++ ostream/streambuf
- C++不会根据需要将数字/数字插入向量
- 代码失败在向量的数据之前插入数字
- 在C++中将破折号删除的文件中的数字插入 BST
- 在二叉树中插入4或5个数字,但输出中只有3个数字
- c++插入数字直到某个符号
- std::string 搜索字符串中的数字并在前后插入空格
- 为什么要在空格中插入数字和特殊字符?