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)
...
}
这篇关于读取由空格或换行符分隔的输入...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:读取由空格或换行符分隔的输入...?


- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01