簡體   English   中英

C在循環中使用int連接字符串

[英]C concatenate string with int in loop

我是C的新手,我遇到了字符串問題。 我想要做的是在循環中創建一個像“val1,val2,val3”的字符串。

目前我的代碼看起來像:

char tagstr[60] = "";
int k;
int n = 5;
for (k=0; k < n; k++) {
    char temp[10]  = "";
    sprintf(temp, ", val%d", k);
    strcat(tagstr, temp);
}

但是tagstr的輸出是“,val#”,其中#是一些長整數值。 我猜這里我的指針做錯了但是我已經嘗試了一切我能想到的但沒有成功......任何幫助都會非常感激。

編輯:更多上下文,如果它有幫助:

int tagsClosed = strlen(pch1) - strcspn(pch1, ")");
do {
    if (curTag.size > 0) {
        // problem section
        char tagstr[60] = "";
        int k;
        for (k = 0; k < 5; k++) {
            char temp[10] = "";
            sprintf(temp, ", val%i", temp, k);
            strcat(tagstr, temp);
        }

        // This prints out something like ", val-890132840" x 5 (same number)
        printf ("String is now: %s\n", tagstr);
    }
    curTag = *(curTag.parent);
    tagsClosed--;
} while (tagsClosed > 0);

curTag是一個結構:

typedef struct Tag {
    char * name;
    int size; // number of children
    int tagnum;
    struct Tag* parent;
} Tag;

問題是sprintf(temp, ", val%i", temp, k); temp的值(實際上是數組中第一個字符的地址)添加到字符串中,並且根本不將k的值添加到字符串中。 這應該是sprintf(temp, ", val%i", k);

您可以提前計算您需要的空間量(包括零終結符):

5+1 + 5+1 + 5+1 + 5+1 + 5+1 + 1 = 31 characters

也; 使用strcat是不好的(因為性能),因為你會反復搜索tagstr ,然后將新字符復制到最后。 最好跟蹤tagstr的當前結束並在最后直接存儲下一組字符,不進行搜索,不進行臨時字符串和無復制。 例如:

void thing(void) {
    char tagstr[60];
    int pos = 0;
    int k;
    int n = 5;

    for (k=0; k < n; k++) {
        pos += sprintf(&tagstr[pos], ", val%d", k);
    }
    printf ("String is now: %s\n", tagstr);
}

適合我:

$ gcc -xc - && ./a.out
int main(void) {
        char tagstr[60] = "";
        int k;
        int n = 5;
        for (k=0; k < n; k++) {
            char temp[10]  = "";
            sprintf(temp, ", val%d", k);
            strcat(tagstr, temp);
        }
        printf("[%s]\n", tagstr);
}
[, val0, val1, val2, val3, val4]

除非你說問題是與最初的", " ..

你的臨時數組太短了! 采用

char temp[16];

如果您決定不想使用前導逗號和空白,則可以對顯示的代碼使用簡單的變體:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char tagstr[60] = "";
    const char *pad = "";
    int k;
    int n = 5;
    for (k = 0; k < n; k++)
    {
        char temp[10]  = "";
        snprintf(temp, sizeof(temp), "%sval%d", pad, k);
        strcat(tagstr, temp);
        pad = ", ";
    }
    printf("tagstr <<%s>>\n", tagstr);
    return 0;
}

該計划的輸出是:

tagstr <<val0, val1, val2, val3, val4>>

但是,您的代碼可以正常工作,雖然使用前導逗號和空白。

temp不足以保存你的sprintf的結果。 這就是為什么你應該使用snprintfstrncat和帶有size參數的字符串函數的其他變體的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM