gpt4 book ai didi

字符处理和字符迭代

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:49 25 4
gpt4 key购买 nike

来源:

#include <stdio.h>

void main()

{

int i, j, tree_Size, spaces, total_Spaces, x;
char tree_Characters;

printf("Enter characters to use --> ");
scanf("%c", &tree_Characters);
printf("Enter size of tree --> ");
scanf("%d", &tree_Size);

//For handling top part of tree
for (i = 0; i <= tree_Size; i++) {
printf("\n");
total_Spaces = tree_Size - i;

//Determine spaces before each number for pyramid
for (spaces = 1; spaces <= total_Spaces; spaces++)
printf(" ");

//Make first line always one number
for (j = -1; j < i; j++)
if (j <= -1)
printf("%c", tree_Characters);
else if (j > -1)
printf("%c%c", tree_Characters, tree_Characters);
}

//For handling stem and base of tree
for (i = 0; i <= tree_Size; i++) {

//if handling stem
if (i < tree_Size) {
printf("\n");
for (spaces = 1; spaces <= tree_Size; spaces++)
printf(" ");
printf("%c", tree_Characters);
}

//else if handling base

else if (i == tree_Size) {
printf("\n");

for (x = 0; x <= tree_Size * 2; x++) {
printf("%c", tree_Characters);
}
}
}

printf("\n");

}

Here is the output it produces so far
Here is a thread I made on reddit for better understanding (comments)

任务的目标是让它看起来像这样:

*** Print a Tree ***

Enter characters to use --- *|=+
Enter size of tree --- 4

*
***
*****
*******
*********
|
|
|
|
====+====

我不明白的是如何处理字符。老师提到将字符放入某个缓冲区然后清除它等,我不知道。谁能帮忙?我必须使用 scanf,无法将任何内容转换为字符串或使用任何高级内容。

最佳答案

您需要使 tree_Characters 成为一个数组(char tree_Characters[5] 用于五元素数组,它将包含四个树字符和一个 nul 终止符),并且更改第一个 scanf。

scanf("%4s%*[^\n]",tree_Characters);
// vv\_____/ ^-- array will decay to char*
// || \-- discard the rest of the line
// || ("*" indicates discard, "[^\n]" matches everything but '\n')
// |\-- string (non-whitespace characters only)
// \-- at most four characters scanned

参见 http://linux.die.net/man/3/scanf获取更多信息。

编辑:您当然必须更改程序的其余部分,以便为每个树元素选择适当的字符。 (参见 @eznme's answer。)

编辑:无数组版本:

char tree_leaf,tree_stem,tree_ground,tree_root;
scanf("%c%c%c%c%*[^\n]",&tree_leaf,&tree_stem,&tree_ground,&tree_root);

这会对太短的输入行产生不良 react 。

关于字符处理和字符迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5206500/

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