我已重定向“cin”以从文件流中读取 cin.rdbug(inF.rdbug())
当我使用提取运算符时,它会一直读取,直到到达空白字符为止。
是否可以使用其他分隔符?我在 cplusplus.com 中浏览了 api,但没有找到任何东西。
最佳答案
可以更改cin
的字间分隔符或任何其他std::istream
, 使用 std::ios_base::imbue
添加自定义ctype
facet
.
如果你正在读取/etc/passwd 样式的文件,下面的程序会分别读取每个:
-delimited word。
#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";
}
}
关于c++ - 更改 cin (c++) 的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302996/