【问题标题】:C: modify array specifec charin cC:在c中修改数组特定的字符
【发布时间】:2021-08-29 14:45:06
【问题描述】:

在这个 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]);
}

【问题讨论】:

    标签: arrays c pointers char scanf


    【解决方案1】:

    函数内

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多