arrays - 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]
被修改两次。似乎在第二次调用中,它是由'\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 码,A
是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
。它允许跳过空格。
推荐阅读
- c - 如何正确进行 GMP 位移?
- r - R,tbl_summary,正确对待连续变量
- sql - 将周聚合分解为日期
- api - 您可以在 google 附近的消息 API 上更新消息吗?
- python - 什么是(for 循环内的 list.index())复杂度
- javascript - 道具类型失败:“object”类型的道具“defaultValue”无效
- python - 我正在尝试导入这个 simpletransformers 得到了错误
- python - 从 requirements.txt 应用 pip freeze 和 pip install 在 2 个 env 之间共享软件版本
- azure - Azure APIM - 策略 - 无法获取有效上下文 - 错误 500 - 对象未设置为对象实例
- html - 如何将网站的最大宽度设置为一定百分比?