希望你一切顺利。
我想知道不使用此语句的 sprintf
的 C++ 等价物是什么?
sprintf(buff, "%-5s", list[idx]);
我正在尝试学习一个教程,其中的目标是使用 C 语言开发带有 Ncurses 库的菜单。但我想用 C++ 来实现。
这是教程中给出的代码:
#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();
}
答案 0 :(得分:5)
%-5s
表示在至少五个字符的字段中打印字符串并左对齐打印,这意味着,如果字符串比字段短,则将其打印在左侧和右侧边用空格填充以填充字段。
在 C++ I/O 流中,您可以使用:
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.
您也可以通过包含 <iomanip>
并使用:
std::cout << std::left << std::setw(5) << list[idx];