简体   繁体   English

使用printf()格式化输出,添加不必要的空格/行-C编程

[英]Formatted output using printf() adding unwanted space/lines - C Programming

This is the function with which I am having the issue. 这是我遇到的问题。 Primarily the printf statement at the end. 最后是printf语句。 I am relatively new to C, however I feel this is an unusual outcome. 我对C还是比较陌生,但是我觉得这是一个不寻常的结果。 Any help would be most appreciated! 非常感激任何的帮助!

void frequencies(char htmlDoc[]) {
    tags(htmlDoc, 0);
    int ndx;
    //  struct tagCounter *pCursor = tagCounters[0];
    int size = 1;
    char *name;
    for (ndx = 0; ndx < tagCntSize; ndx++) {
        name = &(tagCounters[ndx]->tagName[0]);
        while (*(name + 1) != '\0') {
            size++;
            name++;
        }
    name = &(tagCounters[ndx]->tagName[0]);
    char thisName[size];
    int index;
    int thisCount = tagCounters[ndx]->tagCount;
    for (index = 0; index < size; index++) {
        thisName[index] = *name;
        name++;
    }
    printf("%s\t%i\n", thisName, thisCount);
    }
}

This is the resulting output: 这是结果输出:

img
�   1
img
    1
img
    1
img
    1
img
    1
img
    1
Ready
char thisName[size];

After this do 在此之后

memset(thisName,0,sizeof(thisName));

%s expects a null terminated string. %s期望以空终止的字符串。 Or after exiting the loop 或退出循环后

thisName[size] = '\0';

Edits: 编辑:

The array size should be large enough to hold a null termination for a string. 数组大小应足够大以容纳字符串的空终止符。

char thisName[size + 1];

char *name, *ptr; 字符* name,* ptr;

ptr = name = &(tagCounters[ndx]->tagName[0]); ptr =名称=&(tagCounters [ndx]-> tagName [0]);

while (*ptr != '\\0') ptr++; 而(* ptr!='\\ 0')ptr ++;

size = ptr - name; 大小= ptr-名称;

before printf: 在printf之前:

thisName[size] = '\\0'; thisName [size] ='\\ 0';

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

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