开发者

strcat operation with tabs character not working

I am tring to convert an integer array attr of length numAttr to string but separated by tabs '\t' using the below code. If attr[i] = 0, I add just a tab '\t' to attrStr so that that field is empty string. If attr[i] !=0, I convert the integer to string and add to attrStr开发者_运维技巧. But on doing strcat(attrStr,"\t"), no tab character is added to the string. Is there anything specific that I am missing? I hope I am using strcat operation in the right way though. Below is the code:

char *attrStr = new char[len]; strcpy(attrStr,"");
char *buf = new char[buflen]; strcpy(buf,"");
int i = 0;
for (i=0; i<numAttr-1; i++) {
    if (attr[i]!=0) {
        itoa(attr[i],buf,10); 
        strcat(buf,"\t"); 
        strcat(attrStr, buf);
    } else {
        strcpy(buf,"\t"); 
        strcat(attrStr, buf);
    }
}
itoa(attr[i],buf,10); strcat(attrStr, buf);
return attrStr;


Use std::stringstream and std::string. They will make your life simple and easy.

#include <sstream>
#include <string>

std::stringstream ss;
ss << attr[0];
for (i=1; i<numAttr; i++) 
{
    if ( attr[i] )
       ss << "\t" << attr[i];
    else
       ss << "\t"; // If attr[i] = 0, add '\t' to the string (as instructed)
}
std::string s = ss.str();


As others have said, use std::strings. That, formatting, and memory leaks apart, your code looks OKish.

But, how do you know that you don't have tab characters in the string? How are you inspecting it?

Not all IO devices and GUI systems support tabs in the output, so I would look at the char* buffers with a debugger to check if they are really missing.


There are some problems with your code, but in general your code does exactly what it supposed to do. The TAB character is added to the string the way you want it to be added. If you are not seeing it, you must be looking in the wrong place or in the wrong way.

What exactly made you believe that the TAB character is not added?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜