read input separated by whitespace(s) or newline...?(读取由空格或换行符分隔的输入...?)
问题描述
我正在从标准输入流中获取输入.比如,
I'm grabbing input from a standard input stream. Such as,
1 2 3 4 5
或
1
2
3
4
5
我正在使用:
std::string in;
std::getline(std::cin, in);
但这只是抓住了换行符,对吗?如何仅使用 iosteam、字符串和 cstdlib 获取输入是否由换行符或空格分隔?
But that just grabs upto the newline, correct? How can I get input whether they are separated by newline OR whitespace(s) using only iosteam, string, and cstdlib?
推荐答案
只需使用:
your_type x;
while (std::cin >> x)
{
// use x
}
operator>> 默认会跳过空格.您可以链接事物以一次读取多个变量:
operator>> will skip whitespace by default. You can chain things to read several variables at once:
if (std::cin >> my_string >> my_number)
// use them both
getline() 读取一行中的所有内容,无论它是空的还是包含数十个空格分隔的元素,都返回.如果您提供可选的替代分隔符 ala getline(std::cin, my_string, ' ') 它仍然不会执行您似乎想要的操作,例如标签将被读入 my_string.
getline() reads everything on a single line, returning that whether it's empty or contains dozens of space-separated elements. If you provide the optional alternative delimiter ala getline(std::cin, my_string, ' ') it still won't do what you seem to want, e.g. tabs will be read into my_string.
这可能不需要,但您可能很快会感兴趣的一个相当常见的要求是读取单个换行符分隔的行,然后将其拆分为组件...
Probably not needed for this, but a fairly common requirement that you may be interested in sometime soon is to read a single newline-delimited line, then split it into components...
std::string line;
while (std::getline(std::cin, line))
{
std::istringstream iss(line);
first_type first_on_line;
second_type second_on_line;
third_type third_on_line;
if (iss >> first_on_line >> second_on_line >> third_on_line)
...
}
这篇关于读取由空格或换行符分隔的输入...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:读取由空格或换行符分隔的输入...?
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
