C: 修改数组特定字符 c

问题描述

在这个 C 代码中 为什么我不能更改元素 a[0] 的值而我只能输入一次? 如果我想改变元素a[0]的值怎么办?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
char a[20];
char* p;

void klam(void) {
p = a;
scanf("%c",&p[0]);
scanf("%c",&p[0]);
 }
 int main() {

 klam();
 printf("%c",a[0]);
}

解决方法

函数内

void klam(void) {
p = a;
scanf("%c",&p[0]);
scanf("%c",&p[0]);
 }

元素 p[0] 被修改了两次。似乎在第二次调用中,它是由按下 Enter 键后放置在输入缓冲区中的换行符 '\n' 设置的。

这是一个说明问题的演示程序。

#include <stdio.h>

int main(void) 
{
    char c;
    
    scanf( "%c",&c );
    printf( "The code of the character c is %d\n",c );

    scanf( "%c",c );

    return 0;
}

如果输入字符A然后按回车键,程序输出为

The code of the character c is 65
The code of the character c is 10

其中65是字母A的ASCII码,10是换行符'\n'的代码。

按如下方式重写函数

void klam(void) {
p = a;
scanf(" %c",&p[0]);
 }

或者喜欢

void klam(void) {
p = a;
scanf(" %c",&p[0]);
scanf(" %c",&p[0]);
 }

注意函数 %c 调用中转换说明符 scanf 前的空白。它允许跳过空格。