C语言 C在循环中用int连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13169562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:16:09  来源:igfitidea点击:

C concatenate string with int in loop

cstring

提问by user812786

I'm new to C and am having trouble with strings. What I would like to do is create a string like "val1, val2, val3" in a loop.

我是 C 新手,在使用字符串时遇到了麻烦。我想要做的是在循环中创建一个像 "val1, val2, val3" 这样的字符串。

Currently my code looks something like:

目前我的代码看起来像:

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);
}

But the output of tagstr is ", val#", where # is some long integer value. I'm guessing I'm doing something wrong with pointers here but I've tried everything I can think of without success... any help would be much appreciated.

但是 tagstr 的输出是 ", val#",其中 # 是一些长整数值。我猜我在这里的指针有问题,但我已经尝试了所有我能想到的方法但没有成功......任何帮助将不胜感激。

EDIT: more context, if it helps:

编辑:更多上下文,如果有帮助:

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 is a struct:

curTag 是一个结构体:

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

回答by Brendan

The problem is that sprintf(temp, ", val%i", temp, k);adds the value of temp(which is actually the address of the first character in the array) to the string, and doesn't add the value of kto the string at all. This should be sprintf(temp, ", val%i", k);.

问题是sprintf(temp, ", val%i", temp, k);temp(实际上是数组中第一个字符的地址)的值添加到字符串中,而根本没有将值添加k到字符串中。这应该是sprintf(temp, ", val%i", k);

You can calculate the amount of space you'd need in advance (including zero terminator):

您可以提前计算所需的空间量(包括零终止符):

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

Also; using strcatis bad (for performance) because you'd be repeatedly searching for the end of the tagstrand then copying the new characters to the end. It would be better to keep track of the current end of tagstrand store then next group of characters directly at the end with no searching, no temporary string and no copying. For example:

还; usingstrcat不好(为了性能),因为您会反复搜索 的末尾,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);
}

回答by antak

Works for me:

对我有用:

$ 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]

Unless you're saying the problem is with the initial ", "..

除非你说问题出在最初的", "..

回答by Jonathan Leffler

If you decide you don't want the leading comma and blank, you can use a simple variation on the code you showed:

如果您决定不想要前导逗号和空格,您可以对您显示的代码使用一个简单的变体:

#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;
}

The output from the program was:

程序的输出是:

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

However, your code works correctly for me, albeit with the leading comma and blank.

但是,您的代码对我来说可以正常工作,尽管以逗号和空格开头。

回答by Gianluca Ghettini

your temp array is too short! use

你的临时数组太短了!用

char temp[16];

回答by aib

tempisn't long enough to hold the result of your sprintf. This is exactly why you should use snprintf, strncatand other variants of the string functions that take a size parameter, whenever you can.

temp不够长,无法保存您的sprintf. 这正是您应该尽可能使用snprintf,strncat和其他带有 size 参数的字符串函数变体的原因。