名称
get_int - 提示用户从标准输入中输入一行文本,并返回等效的整数
概述
#include <cs50.h>
int get_int(const char *format, ...);
描述
提示用户从标准输入中输入一行文本,并返回等效的整数;如果文本不代表一个整数或会导致溢出,会重新提示用户。
提示的格式类似于 printf(3)。
返回值
返回从标准输入中读取的行的整数等效值,在 [INT_MIN, INT_MAX) 范围内。如果无法读取行,返回 INT_MAX。
示例
/**
* 返回从标准输入中读取的两个整数的和,如果有错误,则返回 INT_MAX。
*/
int add_ints(void)
{
// 从标准输入中读取整数
int i = get_int("输入一个整数: ");
// 确保我们成功读取了一个
if (i == INT_MAX)
{
return INT_MAX;
}
int j = get_int("你想把 %d 加到什么上? ", i);
if (j == INT_MAX)
{
return INT_MAX;
}
return i + j;
}
另见
get_char(3), get_double(3), get_float(3), get_long(3), get_string(3), printf(3)