John Bauer
John Bauer

Reputation: 1

What is the C++ equivalent of this sprintf?

I hope you are going well.

I was wondering what could be the C++ equivalent without using sprintf of this statement?

sprintf(buff, "%-5s", list[idx]);

I am trying to follow a tutorial where the goal is to develop a menu with the Ncurses library in C. But I want to do it in C++.

This is the code given in the tutorial:

#include <ncurses.h>
 
int main() {
     
    WINDOW *w;
    char list[5][7] = { "One", "Two", "Three", "Four", "Five" };
    char item[7];
    int ch, i = 0, width = 7;
 
    initscr(); // initialize Ncurses
    w = newwin( 10, 12, 1, 1 ); // create a new window
    box( w, 0, 0 ); // sets default borders for the window
     
// now print all the menu items and highlight the first one
    for( i=0; i<5; i++ ) {
        if( i == 0 ) 
            wattron( w, A_STANDOUT ); // highlights the first item.
        else
            wattroff( w, A_STANDOUT );
        sprintf(item, "%-7s",  list[i]);
        mvwprintw( w, i+1, 2, "%s", item );
    }
 
    wrefresh( w ); // update the terminal screen
 
    i = 0;
    noecho(); // disable echoing of characters on the screen
    keypad( w, TRUE ); // enable keyboard input for the window.
    curs_set( 0 ); // hide the default screen cursor.
     
       // get the input
    while(( ch = wgetch(w)) != 'q'){ 
         
                // right pad with spaces to make the items appear with even width.
            sprintf(item, "%-7s",  list[i]); 
            mvwprintw( w, i+1, 2, "%s", item ); 
              // use a variable to increment or decrement the value based on the input.
            switch( ch ) {
                case KEY_UP:
                            i--;
                            i = ( i<0 ) ? 4 : i;
                            break;
                case KEY_DOWN:
                            i++;
                            i = ( i>4 ) ? 0 : i;
                            break;
            }
            // now highlight the next item in the list.
            wattron( w, A_STANDOUT );
             
            sprintf(item, "%-7s",  list[i]);
            mvwprintw( w, i+1, 2, "%s", item);
            wattroff( w, A_STANDOUT );
    }
 
    delwin( w );
    endwin();
}

Upvotes: 0

Views: 379

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223389

%-5s says to print a string in a field of at least five characters and to print it left-justified, meaning that, if the string is shorter than the field, it is printed on the left and the right side is padded with spaces to fill the field.

In C++ I/O streams, you can do this with:

    std::cout.width(5);               // Set field width to five.
    std::cout.setf(std::ios::left);   // Request left-justification.
    std::cout << list[idx];           // Insert the string.

You can also do it with I/O manipulators by including <iomanip> and using:

std::cout << std::left << std::setw(5) << list[idx];

Upvotes: 5

Related Questions