简体   繁体   English

使用sprintf,C填写字符串

[英]Filling in a String using sprintf, C

I'm trying to create an array of patterns for a triangle that I'm also printing to the console. 我正在尝试为三角形创建图案阵列,并将其打印到控制台上。 I do this by creating a 2d char array where char patterns [number_of_patterns][pattern_lengths]. 我通过创建一个二维char数组来做到这一点,其中char模式为[number_of_patterns] [pattern_lengths]。 I pass this to a function that takes the array patterns along with the height of the triangle I'm trying to make. 我将其传递给一个函数,该函数采用数组模式以及我要绘制的三角形的高度。

void printTriangle (int rows, char rowPatterns[][rows]) {

    int initialSpaces = rows - 1;
    int numberOfAsterisks = 1;
    int i;

    for (i = 0; i < rows; i++) {
        char temp[rows];
        int spaceCounter = 0;
        int asteriskCounter = 0;

        while (spaceCounter < initialSpaces) {
            printf(" ");
            sprintf(temp, " ");
            spaceCounter++;
        }
        while (asteriskCounter < numberOfAsterisks) {
            sprintf(temp, "*");
            printf("*");
            asteriskCounter++;
        }
        while (spaceCounter < initialSpaces) {
            spaceCounter = 0;
            sprintf(temp, " ");
            spaceCounter++;
        }


        strcpy(rowPatterns[i], temp);
        printf("\n");
        initialSpaces--;
        numberOfAsterisks+=2;
    }

}

For every row of the triangle that I'm printing, I create a string for that row called temp. 对于要打印的三角形的每一行,我为该行创建一个名为temp的字符串。 At the end of the for loop that prints the row to the console and sprintf's it to the array temp, I strcpy temp into patterns[i]. 在将行打印到控制台并将sprintf的行打印到数组temp的for循环结束时,我将temp转换为pattern [i]。 Then I go back to the top of the loop, reinitialize temp to make it fresh, and loop again until I have all my rows. 然后,我回到循环的顶部,重新初始化temp以使其新鲜,然后再次循环直到我拥有所有行。 Except for some reason sprint won't fill in my array temp. 除非出于某些原因,sprint不会填充我的阵列温度。 Is this incorrect use of the function, or does it have to do w my parameter passing? 这是对函数的不正确使用,还是必须通过我的参数传递?

sprintf always writes to the start of the string. sprintf始终写入字符串的开头。 To append, you can maintain a pointer to the end of the string: 要追加,您可以维护一个指向字符串末尾的指针:

char *ptr = rowpatterns[i];

ptr += sprintf(ptr, "*");

You might also hear the suggestion to use strcat - avoid that function. 您可能还会听到使用strcat的建议-避免使用该功能。 When building strings, repeated strcat is very slow and is a common source of performance issues in string code. 在构建字符串时,重复的strcat非常慢,并且是字符串代码中性能问题的常见原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM