unget没有像我想象的那样工作......让我解释一下自己.我认为,unget会获取流中提取的最后一个字符,然后将其放回流中(并准备再次提取).在内部,它正在减少流缓冲区中的指针(创建哨兵和所有东西).
但是,当我在另一个后面使用两个unget()时,它的行为变得非常奇怪.如果写了类似的东西hello<bye,并且我<用作分隔符,如果我使用getline,后来两个ungets,它会返回hello,而不是o<bye".这是我的代码:
#include <iostream>
#define MAX_CHARS 256
using namespace std;
int main(){
char cadena[MAX_CHARS];
cout << "Write something: ";
cin.getline(cadena, MAX_CHARS, '<');
cout << endl << "Your first word delimited by < is: " << cadena << endl;
cin.unget(); //Delimiter (removed by getline) is put back in the stream
cin.unget(); //!?
cin >> cadena;
cout << "Your phrase with 2 ungets done..." << cadena;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试bye<hello,然后cadena得到bye而不是e<hello我认为unget与每次调用时最后一个字符一起工作,f***正在发生什么?