简体   繁体   English

带有制表符的 strcat 操作不起作用

[英]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.我正在尝试使用以下代码将长度为numAttr的 integer 数组attr转换为字符串,但由制表符'\t'分隔。 If attr[i] = 0 , I add just a tab '\t' to attrStr so that that field is empty string.如果attr[i] = 0 ,我只添加一个制表符'\t'attrStr以便该字段为空字符串。 If attr[i] !=0 , I convert the integer to string and add to attrStr .如果attr[i] !=0 ,我将 integer 转换为字符串并添加到attrStr But on doing strcat(attrStr,"\t") , no tab character is added to the string.但是在执行strcat(attrStr,"\t")时,不会将制表符添加到字符串中。 Is there anything specific that I am missing?有什么我遗漏的具体内容吗? I hope I am using strcat operation in the right way though.我希望我以正确的方式使用strcat操作。 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 .使用std::stringstreamstd::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.正如其他人所说,使用 std::strings。 That, formatting, and memory leaks apart, your code looks OKish.那,格式化和 memory 泄漏,你的代码看起来不错。

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.并非所有 IO 设备和 GUI 系统都支持 output 中的选项卡,因此我会使用调试器查看 char* 缓冲区以检查它们是否真的丢失。

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. TAB 字符以您希望的方式添加到字符串中。 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?究竟是什么让您相信没有添加 TAB 字符?

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

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