c++ - 在达到空格字符之前,如何读取未知数量的整数?(C++)
问题描述
我需要从控制台读取数字,;
直到我到达空格字符。输入应如下所示:3;1 -2;-1;1 1;1;3;2
. 每组数字之间可以有多个空格,我需要将每组数字插入到一个向量中。我最初的想法是这样的:
char c;
std::vector<double> coordinates;
while(std::cin >> c){
if(c != ' ' & c != ';'){
double a = c - 48;
coordinates.push_back(a);
}
}
问题在于,如果我有负数,则无法使用 ASCII 将字符转换为整数。如果有人能给我另一种方法来做这种类型的阅读,或者能给我一些建议,我将非常感激!
解决方案
你可以使用istream::peek
:
auto read_sets(std::istream& is) {
std::vector<std::vector<double>> sets;
std::vector<double> current_vector;
double number;
while (is >> number)
{
current_vector.push_back(number);
switch (is.peek())
{
case ';': // ignore semicolons
is.ignore(1);
break;
case ' ': // move to the next set
sets.push_back(std::move(current_vector));
current_vector.clear();
break;
default: // no need to handle dots and digits. EOF is handled in while condition
break;
}
}
sets.push_back(std::move(current_vector)); // push the last set
return sets;
}
推荐阅读
- django - 仅当用户是员工时才使帖子可读
- sql - 如何将while循环转换为CTE
- go - shell提示时自动输入定义的密码?
- perl - Windows 10 64bit 上的草莓 Perl Firebird 驱动程序和模块
- numpy - Numpy 索引在大型矩阵上需要几分钟
- pandas - 尝试在 python 中解析日期时出错
- c# - EF Core 3.0 替换 IMutableIndex.Npgsql() 方法
- python - 如何抓取仅在登录时显示的课程?
- fullcalendar - fullcalendar nextDayThreshold 不起作用。'00:00:00' 显示的时间少了一天
- reactjs - React 挂钩如何从子 Form.Control 设置对 InputGroup 的关注