I am trying to re-read the cin buffer after using cin.getline() 5 times, by calling cin.seekg(), but after calling cin.getline() again, instead of re-reading the data from the top, str becomes an empty string. Does cin.getline() flush the buffer? If so how do I stop that from happening?
#define PATH_MAX 512
using std::cin;
int main()
{
char* str = new char[PATH_MAX + 1];
for(int i = 0; i < 5; i++)
cin.getline(str, PATH_MAX);
cin.seekg(cin.beg);
while(true)
cin.getline(str, PATH_MAX);
return 0;
}
I am trying to re-read the
cin
buffer after usingcin.getline()
5 times
That's not possible with cin
, terminal based input respectively.
What you can do is keeping track of the read input yourself, using a std::vector<std::string>
keeping those lines read in 1st place. Here's a rough sketch:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::string;
int main()
{
std::vector<string> lines;
string line;
for(int i = 0; i < 5; i++) {
std::getline(cin,line);
lines.push_back(line);
}
auto linepos = lines.begin();
while(linepos != lines.end()) {
// cin.getline(str, PATH_MAX); instead do:
// process *linepos
++linepos;
}
}