gpt4 book ai didi

c - 修改并替换C中char数组中的值

转载 作者:行者123 更新时间:2023-11-30 14:56:45 25 4
gpt4 key购买 nike

正如程序所示,我不知道打印出新结果有什么问题。例如当我用position=0、value=v调用modify_str()函数时,结果不会出现“vello”,而是会抛出一段简短的乱码。任何人都可以识别错误!?谢谢:)

#include<stdio.h>
void print_(char *abc);
void modify_str(char *a);

void main(){
char c[20]="Hello";
print_(c);

modify_str(c);

}


void print_(char *str){
int i=0;
while(*(str+i) != '\0'){
printf("%c", str[i]);
i++;
}
printf("\n");
}

void modify_str(char *c){
char q[]="Position of char to modify (0-n): ";
print_(q);
int pos;
scanf("%d", &pos);

printf("value to replace: ");
char w;
scanf("%s", &w);

int index=0;
while(*(c+index) !='\0'){
if(index==pos){
c[index]=w;
printf("New Result: %c\n", c);
}
index++;
}
}

最佳答案

而不是使用不正确的格式说明符进行此调用

scanf("%s", &w);

使用

scanf(" %c", &w);
^^^

while 循环应该如下所示

while( *(c+index) !='\0' && index != pos ) ++index;

if ( index == pos && *( c + index ) != '\0' )
{
c[index]=w;
printf("New Result: %s\n", c);
^^
}

此外,使用标识符 c 命名字符串也是一个坏主意,该标识符通常用于命名 char 类型的对象。最好使用标识符s

考虑到根据 C 标准,不带参数的函数 main 应声明为

int main( void )

顺便说一下,函数print_可以像这样实现

void print_( const char *str )
{
puts( str );
}

并且不要在标识符中使用尾随下划线。这只是一种糟糕的编程风格。

关于c - 修改并替换C中char数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44446604/

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