gpt4 book ai didi

c - 如何从存储的字符串数组中使用 getchar() 函数?

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

我在 Linux 中编写了一个简单的 C 程序,用于从字符串中读取单个字符。我收到一些关于字符串函数的错误。这是我的代码:

#include <stdio.h>
#include <string.h>

void main () {
char arr[10], vv[10];
int i = 0, len;

printf("enter the staement\n");
scanf("%s", arr);
len = strlen(arr);
printf("String laength=%d\n", len);

while ((vv[i] = getchar(arr)) != '\n') {
printf("%d charcter\n");
i++;
}
}

我不想像这样在输入文本上直接使用 getchar():

arr[i] = getchar();

我想从这样存储的字符串中使用 getchar():

getchar(string array);

但不幸的是我得到了一个错误。我可以直接从存储的字符串数组中使用 getchar() 函数吗?

最佳答案

了解 getchar .该链接清楚地表明 getchar 是一个从 stdin 获取字符(unsigned char)的函数。此外,它不需要参数。这意味着您不能使用 getchar 将一个数组的每个字符复制到另一个数组。直接复制就可以了

while( (vv[i] = arr[i]) != '\n')

但我认为这个循环不会结束,因为 scanf 在扫描字符串时包含换行符(%s) .所以,你有两个选择:

  1. 使用 fgets 获取输入。
  2. 使用以下内容

    while( (vv[i] = arr[i]) != '\0')

关于c - 如何从存储的字符串数组中使用 getchar() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567790/

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