类似于 istream::getline() 的东西,但带有替代的 delim 字符
Something like istream::getline() but with alternative delim characters?
获得istream::getline(string, 256, 'n' OR ';')
效果的最干净方法是什么?
我知道写一个循环很简单,但我觉得我可能错过了一些东西。是我吗?
我用的:
while ((is.peek() != 'n') && (is.peek() != ';'))
stringstream.put(is.get());
不幸的是,没有办法有多个"行尾"。您可以做的是阅读该行,例如 std::getline
并将其放入std::istringstream
中,并在istringstream
上的循环中使用std::getline
(带有';'
分隔符)。
尽管您可以查看Boost iostreams库以查看它具有该功能。
有 std::getline。对于更复杂的场景,可以尝试使用提升拆分或regex_iterator拆分istream_iterator或istreambuf_iterator(下面是使用流迭代器的示例)。
这是一个有效的实现:
enum class cascade { yes, no };
std::istream& getline(std::istream& stream, std::string& line, const std::string& delim, cascade c = cascade::yes){
line.clear();
std::string::value_type ch;
bool stream_altered = false;
while(stream.get(ch) && (stream_altered = true)){
if(delim.find(ch) == std::string::npos)
line += ch;
else if(c == cascade::yes && line.empty())
continue;
else break;
}
if(stream.eof() && stream_altered) stream.clear(std::ios_base::eofbit);
return stream;
}
cascade::yes
选项折叠找到的连续分隔符。使用 cascade::no
时,它将为找到的第二个连续分律符返回一个空字符串。
用法:
const std::string punctuation = ",.';:?";
std::string words;
while(getline(istream_object, words, punctuation))
std::cout << word << std::endl;
在Coliru上实时查看其用法
一个更通用的版本将是这个
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 类似于 istream::getline() 的东西,但带有替代的 delim 字符