gpt4 book ai didi

c - 使用指针扫描和打印字符串

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

我编写了一段代码,用于使用指针从用户那里扫描一个字符串并将其存储在另一个字符串数组中并打印该字符串数组。输出变得很奇怪。打印前三个字符,但接下来的字符作为随机垃圾值出现。请告诉我代码中的错误。以下是代码:

#include<stdio.h>
int main(void)
{
char str1[8];
char *p1=str1;
char str2[8];
char *p2=str2;
printf("Enter a string\n");
while(*p1)
scanf("%c",p1++);
*p1='\0';
p1=&str1[0];
while(*p1)
*p2++=*p1++;
*p2='\0';
printf("The copied string is :");
p2=&str2[0];
while(*p2)
printf("%c",*p2++);
}

最佳答案

没有将终止空字符('\0') 放在字符串str1[] 的末尾>str2[]。并且您在第一个 while 循环条件中尝试取消引用并检查未初始化的值:while(*p1)

printf("Enter a string\n");

do{
scanf("%c",p1++);
}while(*(p1 - 1) != '\n'); //try the do while loop

*(p1 - 1) = '\0'; //placing terminating null character

p1 = &str1[0];
while(*p1){
*p2++ = *p1++;
}
*p2 = '\0'; //placing terminating null character

这是演示代码:https://ideone.com/dF2QsJ

Why have you checked the condition for the new line in the do while condition? And why p1-1?

这是因为您通过输入一个 '\n' 来结束输入,它存储在 p1 然后 p1 移动到 p1 + 1 在每次迭代结束时。因此,我检查 '\n' 是否存在于 p1 - 1

关于c - 使用指针扫描和打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41535923/

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