gpt4 book ai didi

C编程: ouput two strings as two columns next to each other

转载 作者:太空狗 更新时间:2023-10-29 15:26:09 24 4
gpt4 key购买 nike

我对我用 C 编写的程序有疑问。我将在两列中并排写两个不同的字符串。我没有找到我的问题的明确答案,因为他们几乎总是给出长度或数量已知的数字示例。

我有两个字符串,最大长度为 1500 个字符,但对我来说长度未知。让我们为了学习而赋予他们这些值(value)观:

char string1[] = "The independent country is not only self-governed nation with own authorities.";
char string2[] = "This status needs the international diplomatic recognition of sovereignty.";

我想把它们并排写,列宽为二十个字符。我已将列之间的差异设置为常规“选项卡”。像这样:

The independent coun     This status needs th
try is not only self e international dipl
-governed nation wit omatic recognition o
h own authorities. f sovereignty.

我已尝试使用以下代码,但它并不有效,因为我无法弄清楚如何使其适应字符串的长度。它也刚好适合写五行。我也收到以下错误。

谁能给我一个例子说明如何做到这一点,也许可以使用预定义的 c 函数以避免使用 for 循环。

void display_columns(char *string1, char *string2);

int main()
{
char string1[] = "The independent country is not only self-governed nation with own authorities.";
char string2[] = "This status needs the international diplomatic recognition of sovereignty.";

display_columns(string1,string2);
}

void display_columns(char *string1, char *string2)
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0+20*i;j<20+20*i;j++)
{
printf("%c",string1[j]);
}

printf("\t");

for(j=0+20*i;j<20+20*i;j++)
{
printf("%c",string2[j]);
}
}
}

最佳答案

我想这是更通用的方法。

void print_line(char *str, int *counter) {

for (int i = 0; i < 20; i++) {
if (str[*counter] != '\0') {
printf("%c", str[*counter]);
*counter += 1;
}
else { printf(" "); }
}
}

void display_columns(char *string1, char *string2)
{
int counter = 0, counter2 = 0;

while (1) {

print_line(string1, &counter);

printf("\t");

print_line(string2, &counter2);

printf("\n");

if (string1[counter] == '\0' && string2[counter2] == '\0') {
break;
}
}
}

关于C编程: ouput two strings as two columns next to each other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com