简体   繁体   中英

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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