首页 > 解决方案 > 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]);
}

标签: arrayscpointerscharscanf

解决方案


函数内

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

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

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

#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 );
    printf( "The code of the character c is %d\n", c );

    return 0;
}

如果输入字符A,然后按 Enter 键,则程序输出将是

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

其中65是字母的 ASCII 码,A10换行符的代码'\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。它允许跳过空格。


推荐阅读