[英]Inserting a new line feed within a character array
我想在一个数组中插入一个新的换行符,这样如果我的数组的字符串长度增加到14以上,则显示的数组的其他内容将显示在输出控制台的新行中。 敌人例如,在下面的程序中,我想在第一行显示“mein hoon don”并在这14个字符之后显示。 我想在输出控制台的新行中显示下一个内容“Don Don Don”。 我读到使用\\ 0xa(hexa)和十进制的\\ 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]='\0';
strcat(abc,"Don Don Don");
cout << "value of abc is " << abc;
getchar();
}
转义序列\\10
不会执行您认为的操作。 代替\\n
可能是最简单的。
注意:您还可以使用strcat
插入换行符并防止出现任何索引计算问题:
strcpy(abc,"mein hoon don.");
/* abc[15]='\10'; */
/* abc[16]='\0'; */
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;
}
更改:
abc[15] = '\10';
abc[16] = '\0';
至:
abc[14] = '\n';
abc[15] = '\0';
那么,逃逸的安全取决于你正在运行的操作系统:有两个caracters \\ r \\ n(运营商返回)和\\ 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 << "\n\n" ;
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 << "\n\n" ;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.