📄 ioutils.cpp
字号:
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "IoUtils.h"
using namespace std;
/* 从cin读入一行文字
* 跳过行首空白, 确保返回值不为空字符串
*/
string getString() {
const char eol = '\n';
const int buffer_size = 120;
int c;
string x;
while ((c = cin.get()) && (cin) && isspace(c)); // 跳过空白
if (char(c)==eol) { // 没有内容
x = "";
return x;
}
char buffer[buffer_size+1];
int i = 0;
do {
buffer[i++] = char(c);
} while ((c = cin.get()) && cin && char(c)!=eol && i!=buffer_size);
buffer[i] = '\0';
x = buffer;
if ( cin && char(c)!=eol ) { // 还没读到eol
cin.putback(c);
string remainder = getString(); // 继续读
x += remainder;
}
return x;
} // getString()
/* 从cin读入一个int值
*/
int getInteger() {
int val;
for (;;) {
string str = getString();
if ( ( val = atoi(str.c_str()) ) != 0 ) { // 转换成功
return val;
} else { // 如果输入值确实是0, 返回0
if (str[0] == '-' || str[0] == '+') {
if (str[1] == '0')
return val;
} else
if (str[0] == '0') {
return val;
}
}
cout << "输入有误! 请输入一个整数值: ";
}
} // getInteger()
/* 从cin读入一个double值
*/
double getDouble() {
double val;
for (;;) {
string str = getString();
if ( ( val = atof(str.c_str()) ) != 0.0 ) { // 转换成功
return val;
} else { // 如果输入值确实是0.0, 返回0.0
if (str[0] == '-' || str[0] == '+') {
if (str[1] == '0')
return val;
} else
if (str[0] == '0') {
return val;
}
}
cout << "输入有误! 请输入一个数值 (可以有小数): ";
}
} // getDouble()
/* 从cin读入一个正整数值
*/
int getPositiveInteger() {
int val;
for (;;) {
string str = getString();
if ( ( val = atoi(str.c_str()) ) > 0 ) {
return val;
}
cout << "输入有误! 请输入一个正整数值: ";
}
} // getPositiveInteger()
/* 在屏幕上打印 "Press any key to continue..."
* 并在等待用户按任意键后返回
*/
void pause() {
cout << "Press any key to continue...";
getch();
cout << endl;
} // pause()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -