C++iostream读取,分隔符为MULTIPLE字节

C++ iostream read with delimiter of MULTIPLE bytes

本文关键字:MULTIPLE 字节 分隔符 读取 C++iostream      更新时间:2023-10-16

我们知道要从输入流中读取,我们可以使用以下标准C++函数

istream& getline (char* s, streamsize n, char delim );

但是,我们只能提供一个字节/字符的分隔符。

如果我希望使用多个字节的分隔符,该怎么办?有什么巧妙的东西我可以利用,推动吗?

最佳,
Lyn

我认为您可以使用cin.get()而不是cin.getline()。每次读取一个字符,并测试是否出现分隔符。

int main(void){

string str;  
int length_of_delimiter = 3;  
const char *delimiter = "ABC";  
char temp = '0';  
bool over = false;  
cout<<"Enter the stream"<<endl;
temp =  cin.get();
int  i = 0;
while(over == false){ 
        for(i = 0; temp  == delimiter[i] && i < length_of_delimiter; i++){
            str += temp;
            temp = cin.get();
        }
        if(i == length_of_delimiter){
            //chop off the delimiter
            str.erase(str.end() - length_of_delimiter, str.end());
            over = true;
        }
        else {
            str += temp;
            temp = cin.get();
        }
}
cout<<"The stream we wanted is: "<<str<<endl;
return 0;

}