#CS50202. 完善程序2-字符处理-2读入整数

完善程序2-字符处理-2读入整数

读入整数

请完善下面的程序,使得程序能够读入两个 int 范围内的整数, 并将这两个整数分别输出,每行一个。

输入的整数之间和前后只会出现空格或者回车。输入数据保证合法。

例如:

输入:

123  -789

输出:

123  

-789

程序:

#include <iostream>
using namespace std;
int readint(){
    int num = 0;          // 存储读取到的整数
    int negative = 0;    // 负数标识
    char c;                  // 存储当前读取到的字符
    c = cin.get();
    while ((c < '0' || c > '9') && c != '-')
        c = ①;
    if (c == '-')
        negative = 1;
    else
        ②;
    c = cin.get();
    while (③){
        ④;
        c = cin.get();
    }

    if (negative == 1)
        ⑤;
    return num;
}
int main()
{
    int a, b;
    a = readint();
    b = readint();
    cout << a << endl
         << b << endl;
    return 0;
}
  1. ①处应填( ){{ select(1) }}
  • c-'0'
  • '0'
  • c+'0'
  • cin.get()
  1. ②处应填( ){{ select(2) }}
  • num=0
  • num=c-'0'
  • num=c-'a'
  • num=c
  1. ③处应填( ){{ select(3) }}
  • c>='0'&&c<='9'
  • c>='a'&&c<='z'
  • c<'0'||c>'9'
  • c!='-'
  1. ④处应填( ){{ select(4) }}
  • num=num+c-'0'
  • num=num*10+c-'0'
  • num=num+c
  • num=num*10+c
  1. ④处应填( ){{ select(5) }}
  • num=-num
  • num=num+num
  • num--
  • num++