在字符数组中插入新的换行符



我想在数组中插入一个新的换行,这样,如果数组的字符串长度增加到超过14,则在输出控制台的新行中显示数组的其他内容。在下面的程序中,我想在第一行和这14个字符之后显示"mein hoon don"。我想在输出控制台的新行中显示下一个内容"Don Don Don"。我读到,使用xa(十六进制)和10在十进制换行。但是当我试图在我的代码中使用它们时,我无法产生期望的输出。

# include <iostream.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main()
{
    char abc[40];
    strcpy(abc,"mein hoon don.");
    abc[15]='10';
    abc[16]='';
    strcat(abc,"Don Don Don");
    cout << "value of abc is " << abc;
    getchar();
}

变化:

abc[15] = '10';
abc[16] = '';

:

abc[14] = 'n';
abc[15] = '';

转义序列10并不像您想象的那样。使用n可能是最简单的方法。

注意:您也可以使用strcat插入换行符,以防止任何索引计算问题:

strcpy(abc,"mein hoon don.");
/* abc[15]='10'; */
/* abc[16]=''; */
strcat(abc, "n");
strcat(abc,"Don Don Don");

你真的最好使用std::string而不是char数组:

#include <iostream>
#include <string>
int main() {
    std::string s;
    s = "mein hoon don.";
    s += "n";
    s += "Don Don Don";
    std::cout << value of abc is " << s << std::endl;
    return 0;
}

好吧,转义顺序取决于您正在工作的操作系统:有两个字符r(承运人返回)和n(换行),在windows中,您需要两个字符,在linux中,您只需要r,在Mac中,您需要n。

但是,只要你在使用cpp,你不应该使用它们中的任何一个,你应该使用endln来代替:

//# include <stdio.h>
//# include <stdlib.h>
//# include <string.h>
#include <ostream>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
    //char abc[40];
    std::ostringstream auxStr;
    auxStr << "mein hoon don." << std::endl << "Don Don Don" << std::endl;
    //if you need a string, then:
    //std::string abc = auxStr.str();
    std::cout << "value of abc is " << auxStr.str();
    getchar();
}

这段代码在x位置引入了一个换行条件。

只要设置Line_Break=14;就可以了。

# include <iostream.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main()
{
    int LinePos=0; 
    int Line_Break_Pos=0;
    int Line_Break=10;
    char abc[40]={""};
    strcpy(abc,"mein hoon don. ");
    strcat(abc,"Don Don Don");
    cout << "n" ;
    cout << "Without linebreak : n";
    cout << abc ;
    cout << "nn" ;
    cout << "With linebreak    : n" ;

     while (LinePos < strlen(abc) )
     {
         cout <<abc[LinePos];
         if (Line_Break_Pos > Line_Break && abc[LinePos ]==' ')
         {
             cout << "n" ;
             Line_Break_Pos=0;
         }
         LinePos++;
         Line_Break_Pos++;
     }

    cout << "nn" ;
    return 0;
}

最新更新