LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   No Return to Command Line in C++ (https://www.linuxquestions.org/questions/programming-9/no-return-to-command-line-in-c-622708/)

unihiekka 02-21-2008 03:23 AM

No Return to Command Line in C++
 
In my C++ programme, the main function calls a routine ShowGraphs, in which gnuplot is opened, plots some data to the screen, and then exits gnuplot when I press q (as usual in gnuplot). However, after the graphs disappear from the screen the programme does not return to the command line, but only if I terminate the programme with Ctrl+C or press s and then Enter, because I have inserted a most unappealing while loop:
Code:

int ShowGraphs()
{
 FILE *GnuPlot = popen("/usr/bin/gnuplot", "w");
 if(!GnuPlot)
  {
  cerr << "Not able to open GnuPlot: " << strerror(errno) << '\n';
  return 0;
  }

 (...)

 while(1)
 {
  if ('s' == getchar() )
  {
  pclose(GnuPlot);
  return 1;
  }
 }
}

If I do not insert the loop at the end of the ShowGraphs the programme executes correctly, but shows the graphs and removes them instantly from the screen, which is not what I want - I want to see them for a while. Is there a nice way (preferably without ncurses, if it's not too much of a fuss) to circumvent the problem and exit the main programme to the command line after I have watched the graphs for a while and pressed 'q', without then pressing s and then Enter? Just for the record, the ShowGraphs function is the last to be executed in the main function.

paulsm4 02-21-2008 12:23 PM

Hi -

I think "getchar()" already has exactly the functionality you're looking for (just wait, until the user types something in and hits <Enter> ... or, more simply, until the user just hits <Enter>...)

Try this:
Code:

int ShowGraphs()
{
  FILE *GnuPlot = popen("/usr/bin/gnuplot", "w");
  if(!GnuPlot)
  {
    cerr << "Not able to open GnuPlot: " << strerror(errno) << '\n';
    return 0;
  }

  (...)

  int c;
  while((c = getchar ()) != 'q')
    ;
  pclose(GnuPlot);
  return 1;
}

... or ...
Code:

  getchar ();
  pclose(GnuPlot);

'Hope that helps .. PSM

unihiekka 02-22-2008 07:24 AM

I didn't think of the last one, which is actually very simple and neat, thanks. What I'd really like is that it quits the programme after the gnuplot graphs have been closed by 'q', but for the time being I'm happy with it.


All times are GMT -5. The time now is 04:19 AM.