-
Redirecting cin?
I can easily redirect the standard output to the terminal but getting the standard input to redirect to the terminal isn't working. I'm stumped.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[]){
string username;
char c;
ifstream termin("/dev/tty");
ofstream termout("/dev/tty");
termout << "Enter SQL user name: ";
termout.flush();
// termin.getline(username, 16); //didn't work
// termin >> username; //Me neither
// while ((c = termin.get()) > ' ');//Nope
cout << username << endl;
}
Easy newbie mistake?
[edit]
Code:
while (isgraph(c = cin.get())) username += c;
does work but, of course, that won't handle redirected input.
[/edit]
-
I don't know if this will fix your problem, but:
Code:
> termin.getline(username, 16);
//This should be:
getline(termin,username);
-
Thanks swoopy. No that did work either... oh well. It seems that for some things I have to drop into c proper because either c++ can't do it or because it's extremely non-intuitive to do in c++. It's all part of the learning process.
-
Remembering that stdin is a file pointer, just freopen() it as your tty.
-
Thanks Imperito too. I saw the freopen solution while googling. Here's my very C-ish solution (see below). I'm new to c and even newer to c++. What I'm doing is trying to make the classes a bit more C++ish. Like making the char* become a string object & the printf become cout etc. Along the way I'm running into some SNAFUs that don't seem to fit the c++ paradigm but work quite easily in the "lower level" language. It's a matter of learning which tool is right for the job. At least c++ allows c code & if I really feel the need I can in-line assembly a lib or something.
Code:
//#############################################################################
//UserName = Prompt for same --- A work in progress
//#############################################################################
void DB::UserName(char* user) throw (TerminalError){
FILE* ttyin; //Redirect input to the terminal
FILE* ttyout; //Redirect output to the terminal
//=========================================================================
// Need to redirect i/o to the terminal for this prompt
//=========================================================================
ttyin = fopen("/dev/tty", "r");
ttyout = fopen("/dev/tty", "w");
if (!ttyin || !ttyout){
if (ttyin) fclose(ttyin);
if (ttyout) fclose(ttyout);
throw TerminalError();
}
//=========================================================================
// Now prompt for the SQL user name
//=========================================================================
fprintf(ttyout, "Enter SQL username: ");
fflush(ttyout);
fgets(user, 16, ttyin);
for (int i = 0; user[i] && i < 16; i++) if (user[i] == '\n') user[i] = 0;
fclose(ttyin);
fclose(ttyout);
}
Another thing I'm trying to avoid is writing wrappers around wrappers which seems to be a pitfall for an OO newbie.