#include <iostream>
#include <cctype> // isdigit
using namespace std;
// Global buffer
const int LINE_LENGTH = 128;
char line[LINE_LENGTH];
int lineIndex;
void getLine () {
// Get a line of characters.
// Install a newline character as sentinel.
cin.getline (line, LINE_LENGTH);
line[cin.gcount () - 1] = '\n';
lineIndex = 0;
}
enum State {eI, eF, eM, eSTOP};
void parseNum (bool& v, int& n) {
int sign;
State state;
char nextChar;
v = true;
state = eI;
do {
nextChar = line[lineIndex++];
switch (state) {
case eI:
if (nextChar == '+') {
sign = +1;
state = eF;
}
else if (nextChar == '-') {
sign = -1;
state = eF;
}
else if (isdigit (nextChar)) {
sign = +1;
n = nextChar - '0'; // line 41
state = eM;
}
else {
v = false;
}
break;
case eF:
if (isdigit (nextChar)) {
n = nextChar - '0';
state = eM;
}
else {
v = false;
}
break;
case eM:
if (isdigit (nextChar)) {
n = 10 * n + nextChar - '0';
}
else if (nextChar == '\n') {
n = sign * n;
state = eSTOP;
}
else {
v = false;
}
break;
}
}
while ((state != eSTOP) && v);
}
int main () {
bool valid;
int num;
cout << "Enter number: ";
getLine();
parseNum (valid, num);
if (valid) {
cout << "Number = " << num << endl;
}
else {
cout << "Invalid entry." << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第41行中的'0'是什么意思?这行是否指定下一个字符减去nextChar的第一个字符?
nextChar - '0'返回字符的整数值.例如,如果字符值为'1'(即ASCII 0x31),那么如果减去'0'(即0x30),则得到值1.由于ASCII值'0' - '9'是连续的,因此技术会起作用.
它将nextChar中引用的数字(ASCII)转换为实际值.因此,如果ASCII值为'5',则从'5'减去'0'会得到数值5.
此转换允许您对通过键盘输入的值执行数学运算.
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |