[英]using isDigit to find charecters c++
试图弄清楚如何使用 isDigit 忽略字符串中除 x、X、e、E 之外的每个字符。 正如您在下面看到的,我正在使用 x 等于 10 和 e 等于 11(不区分大小写)对十进制进行十进制。 cin.ignore() 遇到问题。 output 应为 36。字符串 duo 应先读取 3,然后读取 0,并否定 rest。
#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;
}
下面我修改了您的代码,以便它给出正确的答案。 对于输入30-something
左右,它给出36
作为 output。
据我了解,您想在30
之后立即完成转换,即 ignore -something
。 对于这种行为,我在我的代码中放置了一个标志stop_on_first_non_digit
,如果它是true
,那么它会在第一个非数字字符上结束。 但是您可以将其设置为false
,然后我只跳过非数字字符,但使用所有数字字符,例如-something
中包含e
,因此包含一个数字,如果stop_on_first_non_digit
为false
,则将使用这个单个e
数字。 现在默认情况下它是true
,所以它的行为方式是你喜欢的。
此外,我保留了跳过字符串中第一个空格的逻辑,因此您可以输入30-something
左右(前导空格),它也提供36
。
#include <string>
#include <cctype>
#include <iostream>
int main() {
std::string duo = "30-something";
bool stop_on_first_non_digit = true;
size_t i = 0;
int decValue = 0;
while (i < duo.length() && std::isspace(duo.at(i)))
++i;
for (; i < duo.length(); ++i) {
char c = duo.at(i);
int digit = 0;
if (std::isdigit(c))
digit = c - '0';
else if (c == 'x' || c == 'X')
digit = 10;
else if (c == 'e' || c == 'E')
digit = 11;
else {
if (stop_on_first_non_digit)
break;
else
continue;
}
decValue *= 12;
decValue += digit;
}
std::cout << decValue << std::endl;
}
Output:
36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.