0

I am Completely new to programming. I am trying to make a very basic Ncurses game. My problem is that I have some very repetitive code where I take a string, calculate the length of it, divide it by 2, then subtract from the amount of columns. I do this so I can center my text on the screen. I want to make this easier by making a function, but I don't know how to make a function that returns the Ncurses function mvprintw(y,x,string)

Here is my code so you can understand better:

#include <iostream>
#include <ncurses.h>
#include <string.h>

int main(){

initscr();

int x,y;

    getmaxyx(stdscr, y, x);
    mvprintw(0,x/2-(strlen("************")/2), "************");
    mvprintw(1,x/2-(strlen("Welcome")/2), "Welcome");
    mvprintw(2,x/2-(strlen("************")/2), "************");
    refresh();
    getch();

endwin();
return 0;
}
  • 1
    Your code is C (except for `` which is useless). Regarding your title (which is *unrelated* to your code), in C++11, you would use [closures](https://en.wikipedia.org/wiki/Closure_%28computer_programming%29) to *return* a function (as some value). Probably with [lambdas](http://en.cppreference.com/w/cpp/language/lambda) & [std::function](http://en.cppreference.com/w/cpp/utility/functional/function) – Basile Starynkevitch Nov 11 '16 at 21:45

3 Answers3

2

You figure out what parameters the operation you want to perform depends on, and so you know what to pass. Then it's as easy as writing the operations, whilst substituting the parameter names for the actual parameters.

void center_text(int y, int x, char const* text) {
  mvprintw(0,x/2-(strlen(text)/2), text);
}

Once you have that, just use it:

getmaxyx(stdscr, y, x);
center_text(0, x, "************");
center_text(1, x, "Welcome");
center_text(2, x, "************");
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Okay I see, so the return type is void and the statements inside will do what I want. I don't know why I didn't see that. THank you! – Daniel Cory Nov 11 '16 at 21:29
1

I believe, that is what you need:

void centered(const char* str, int &x){
    static int count = 0;
    mvprintw(count,x/2-(strlen(str)/2), str);
    count++;
}

....

centered("************", x)
centered("Welcome", x)
centered("************", x)

But you should learn about functions before trying to write them (obviously)

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
1

Here is a function that will do the job:

static void printCentered(int y, int x, char * text) {
    mvprintw(y, x - (strlen(text) / 2), text);
}

I modified the centering calculation assume that x represents the center line. You can then use this function instead of directly calling mvprintw.

printCentered(0, x, "***************");
printCentered(1, x, "Welcome");
printCentered(2, x, "***************");
tddguru
  • 392
  • 1
  • 4