gpt4 book ai didi

c - 将空间扫描为字符

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:56 24 4
gpt4 key购买 nike

所以我有一个简单的代码可以扫描单词的每个字母并使用指针写入它的值和地址。

我的问题是 %c 不扫描空格,而我希望它们扫描。我该如何管理?

#include <stdio.h>

int main()
{
char c1, c2, *p_c;
while (scanf_s(" %c", &c1) == 1)
{
if (c1 == '*')
break;
p_c = &c1;
c2 = *p_c;
printf("c1: %c (%p) c2: %c (%p) c_p: %c (%p)\n", c1, &c1, c2, &c2, *p_c, p_c);
}

return 0;
}

例如

输入:

is this C?*

预期输出:

c1: i (00D3F7CF) c2: i (00D3F7C3) c_p: i (00D3F7CF)
c1: s (00D3F7CF) c2: s (00D3F7C3) c_p: s (00D3F7CF)
c1: (00D3F7CF) c2: (00D3F7C3) c_p: (00D3F7CF)
c1: t (00D3F7CF) c2: t (00D3F7C3) c_p: t (00D3F7CF)
c1: h (00D3F7CF) c2: h (00D3F7C3) c_p: h (00D3F7CF)
c1: i (00D3F7CF) c2: i (00D3F7C3) c_p: i (00D3F7CF)
c1: s (00D3F7CF) c2: s (00D3F7C3) c_p: s (00D3F7CF)
c1: (00D3F7CF) c2: (00D3F7C3) c_p: (00D3F7CF)
c1: C (00D3F7CF) c2: C (00D3F7C3) c_p: C (00D3F7CF)
c1: ? (00D3F7CF) c2: ? (00D3F7C3) c_p: ? (00D3F7CF)

我的代码完全跳过空格,就好像它们根本不存在一样。提前致谢。

最佳答案

编码错误

"%c" with scanf_s() 需要 2 个参数,rsize_tchar*
这也意味着编译可能无法在启用所有警告的情况下完成。
节省时间,启用所有警告。

The scanf_s function is equivalent to fscanf_s with the argument stdin interposed before the arguments to scanf_s. C11dr §K.3.5.3.4 4

The fscanf_s function is equivalent to fscanf except that the c, s, and [ conversion specifiers apply to a pair of arguments ... §K.3.5.3.2 4

// scanf_s(" %c", &c1)
scanf_s(" %c", &c1, sizeof c1)

My problem is that %c doesn't scan spaces, and I would like them to. How do I manage that?

"" 消耗空白

为了' '那样消耗空白,省略前导""

// scanf_s(" %c", &c1, sizeof c1)
scanf_s("%c", &c1, sizeof c1)

或者用 scanf() 简化

scanf("%c", &c1)

或者使用 getchar() 进一步简化

char c1;
int ich;
while ((ich = getchar()) != EOF) {
c1 = (char) ich;
...

关于c - 将空间扫描为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53127959/

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