[英]using isDigit to find charecters c++
Trying to figure how I can use isDigit to ignore every character except x, X, e, E within a string.试图弄清楚如何使用 isDigit 忽略字符串中除 x、X、e、E 之外的每个字符。 As you can see below I'm doing duodecimal to decimal with x equal to 10 and e equal to 11 (not case sensitive).正如您在下面看到的,我正在使用 x 等于 10 和 e 等于 11(不区分大小写)对十进制进行十进制。 Having trouble with cin.ignore(). cin.ignore() 遇到问题。 The output should be 36. The string duo should read in the 3 then 0 and negate the rest. 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;
}
Below I modified your code so that it gives correct answer.下面我修改了您的代码,以便它给出正确的答案。 For input 30-something
it gives 36
as output.对于输入30-something
左右,它给出36
作为 output。
As I understood you want to finish conversion right after 30
ie ignore -something
.据我了解,您想在30
之后立即完成转换,即 ignore -something
。 For such behaviour I put a flag stop_on_first_non_digit
in my code, if it is true
then it finishes on first non-digit character.对于这种行为,我在我的代码中放置了一个标志stop_on_first_non_digit
,如果它是true
,那么它会在第一个非数字字符上结束。 But you may set it to false
then I just skip non-digit chars but use all chars that are digits, for example -something
has e
in it, so contains one digit, if stop_on_first_non_digit
is false
then this single e
digit will be used.但是您可以将其设置为false
,然后我只跳过非数字字符,但使用所有数字字符,例如-something
中包含e
,因此包含一个数字,如果stop_on_first_non_digit
为false
,则将使用这个单个e
数字。 By default now it is true
so that it behaves the way you like.现在默认情况下它是true
,所以它的行为方式是你喜欢的。
Also I kept your logic of skipping first spaces in a string so you can input 30-something
(leading spaces) and it gives 36
too.此外,我保留了跳过字符串中第一个空格的逻辑,因此您可以输入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: Output:
36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.