问题描述
我正在从标准输入流中获取输入.比如,
I'm grabbing input from a standard input stream. Such as,
或
我正在使用:
但这只是抓住了换行符,对吗?如何仅使用 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?
推荐答案
只需使用:
operator>>
默认会跳过空格.您可以链接事物以一次读取多个变量:
operator>>
will skip whitespace by default. You can chain things to read several variables at once:
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...
这篇关于读取由空格或换行符分隔的输入...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!