Reputation: 3
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;
}
Upvotes: 0
Views: 92
Reputation: 392
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, "***************");
Upvotes: 1
Reputation: 12140
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)
Upvotes: 1
Reputation: 170259
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, "************");
Upvotes: 2