0

我想知道如何在字符串文本中插入一个空格(在 char *text = argv[1]; 中定义)

例如,如果写:


./mar "你好,你好吗"


我想看看/


你好 你好吗 你好 你好吗 你好 你好吗 你好 你好吗

并不是


你好你好吗你好你好吗你好你好吗你好你好吗你好

在 cli 中水平滚动。

代码是:

/*mar.c*/
#include <curses.h>
#include <unistd.h> // For sleep()
#include <string.h> // For strlen()
#include <stdlib.h> // For malloc()
#include <sys/select.h>

int main(int argc, char* argv[])
{

char *text = argv[1];
char *scroll;
int text_length;
int i,p, max_x, max_y;


// Get text length
text_length = strlen(text);

// Initialize screen for ncurses
initscr();

// Don't show cursor
curs_set(0);

// Clear the screen
clear();

// Get terminal dimensions
getmaxyx(stdscr, max_y, max_x);

scroll = malloc(2 * max_x + 1);

for (i=0; i< 2*max_x; i++) {
    getmaxyx(stdscr, max_y, max_x);    
    scroll[i] = text[i % text_length];
}

scroll[2*max_x - 1]='\0';


// Scroll text back across the screen
p=0;
do{
        getmaxyx(stdscr, max_y, max_x);
        mvaddnstr(0,0,&scroll[p%max_x], max_x);
        refresh();
        usleep(40000);
    p=p+1;
// Execute while none key is pressed   
}while (!kbhit());

endwin();
return 0;
}

int kbhit(void)
{
struct timeval tv;
fd_set read_fd;

tv.tv_sec=0;
tv.tv_usec=0;
FD_ZERO(&read_fd);
FD_SET(0,&read_fd);

if(select(1, &read_fd, NULL, NULL, &tv) == -1)
return 0;

if(FD_ISSET(0,&read_fd))
return 1;

return 0;
} 
4

1 回答 1

0

You need to allocate a new char array whose length is 2 bytes greater than the length of the argument string (so that there's room both for the space and for the null terminator). Then, call strcpy to copy the argument string into the new array, overwrite the second-to-last index with a space and put a null terminator into the last index.

于 2011-02-28T13:25:10.663 回答