C++ std::ifstream 读取字符串分隔符
使用时:
string s;
cin >> s;
字符串可以包含哪些字符以及哪些字符将停止对字符串的读取。
When using:
string s;
cin >> s;
Which characters can string contain and which characters will stop the reading to string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::ctype_base::space
是std::istream
的分隔符,它使其停止从源读取更多字符。std::ctype_base::space
指的是空格和换行符。这意味着,当使用cin>>s
读取时,s
可以包含除空格和换行符之外的任何字符。如果您还想读取包含空格的完整行,则可以使用
getline()
函数使用换行符作为分隔符。还有它的重载函数,如果您想提供自己的分隔符,可以使用它。 有关更多详细信息,请参阅其文档。您还可以使用自定义的区域设置,将其设置为
std::istream
。您的自定义区域设置可以定义一组由std::istream
视为分隔符的字符。您可以在这里看到一个这样的示例(请参阅我的解决方案):对将 std::string 拆分为向量 的方法
std::ctype_base::space
is the delimiter forstd::istream
which makes it stop reading further character from the source.std::ctype_base::space
refers to whitespace and newline. That means,s
can contain any character except whitespace and newline, when reading usingcin>>s
.If you want to read complete line containing whitespaces as well, then you can use
getline()
function which uses newline as delimiter. There also exists its overloaded function, which you can use if you want to provide your own delimiter. See it's documentation for further detail.You can also use customized locale which you can set to
std::istream
. Your customized locale can define a set of characters to be treated as delimiter bystd::istream
. You can see one such example here (see my solution):Right way to split an std::string into a vector<string>
分隔符是任意字符
ch
,其中std::isspace( ch,
返回 true。换句话说,无论std::sin.getlocale() )
充满的语言环境考虑“空白”。 (虽然我会
认为这有些滥用,我知道程序员会创建
特殊的语言环境,考虑例如
,
空白,并使用>>
读取逗号分隔的列表。)The delimiter is any character
ch
for whichstd::isspace( ch,
returns true. In other words, whateverstd::sin.getlocale() )
the imbued locale considers "white space". (Although I would
consider it somewhat abuse, I've known programmers to create
special locales, which consider e.g.
,
white space, and use>>
to read a comma separated list.)