更改cin(c ++)的分隔符 [英] changing the delimiter for cin (c++)
问题描述
我已重定向cin从文件流读取 cin.rdbug(inF.rdbug())
当我使用提取操作符
I've redirected "cin" to read from a file stream cin.rdbug(inF.rdbug())
When I use the extraction operator it reads until it reaches a white space character.
是否可以使用另一个分隔符?
Is it possible to use another delimiter? I went through the api in cplusplus.com, but didn't find anything.
推荐答案
可以改变inter- cin
的字分隔符或任何其他 std :: istream
,使用 std :: ios_base :: imbue
添加自定义< a href =http://en.cppreference.com/w/cpp/locale/ctype> ctype
facet
。
It is possible to change the inter-word delimiter for cin
or any other std::istream
, using std::ios_base::imbue
to add a custom ctype
facet
.
如果您正在以/ etc / passwd风格读取文件,以下程序将分别读取每个:
限定词。
If you are reading a file in the style of /etc/passwd, the following program will read each :
-delimited word separately.
#include <locale>
#include <iostream>
struct colon_is_space : std::ctype<char> {
colon_is_space() : std::ctype<char>(get_table()) {}
static mask const* get_table()
{
static mask rc[table_size];
rc[':'] = std::ctype_base::space;
rc['\n'] = std::ctype_base::space;
return &rc[0];
}
};
int main() {
using std::string;
using std::cin;
using std::locale;
cin.imbue(locale(cin.getloc(), new colon_is_space));
string word;
while(cin >> word) {
std::cout << word << "\n";
}
}
这篇关于更改cin(c ++)的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!