【发布时间】:2025-11-29 05:45:01
【问题描述】:
试图弄清楚如何使用 isDigit 忽略字符串中除 x、X、e、E 之外的每个字符。正如您在下面看到的,我正在使用 x 等于 10 和 e 等于 11(不区分大小写)对十进制进行十进制。 cin.ignore() 遇到问题。输出应该是 36。字符串 duo 应该读入 3 然后 0 并否定其余部分。
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
using namespace std;
main() {
using str_t = std::string::size_type;
str_t idx = 0;
int decValue = 0;
string duo = "30-something";
while (isspace(duo.at(idx)) && idx < duo.length()) {
idx++;
}
for (std::string::size_type i = 0; i < duo.length(); ++i) {
decValue *= 12;
if (isdigit(duo.at(i))) {
decValue += duo.at(i) - '0';
}
else if (duo.at(i) == 'x' || duo.at(i) == 'X') {
decValue += 10;
}
else if (duo.at(i) == 'e' || duo.at(i) == 'E') {
decValue += 11;
}
/// Program works if this executable line is taken out
else if (!char.isDigit(duo.at(i))) {
cin.ignore();
}
}
cout << decValue << endl;
}
【问题讨论】:
-
为什么要
std::isdigit()?如果您只关心 X 和 E,那么检查它是 X 还是 E 不是更简单吗?您甚至可以使用std::tolower()或std::toupper()(经销商的选择)来简化检查。 -
为什么要
ignore?cin没有其他用途。总而言之,这是一个令人困惑和困惑的问题。 -
如果我理解正确,您应该将
std::string从base-12 转换为base-10?这是如何运作的? Base-12 应该是 0-9 + AB,对吧? -
终于找到了抛出错误的注释行,这是非常糟糕的语法。那条线的目标是什么,为什么它与您的其他检查如此不同?也许是复制/粘贴?
-
回到问题的文本,您声称应该读入 3 并且所有其他内容都被否定,但是您的字符串中有
e,您声称您不想这样做忽视。那么它是什么?