c - 如何使用指针正确地将字符串输入存储到字符数组中?

标签 c arrays string pointers

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char string[100];
    int count=0;

    char *pString = string;

    printf("Enter a string: \n");
    scanf("%s",string);

    while(*pString != '\0')
        count++;

    printf("String is %d characters long",count);


    return 0;
}

这是我的代码。我想编写一个简单的函数来计算字符串数组中的字符数。问题是我输入字符串后它就卡住了。控制台就卡住了。它不会释放输出。

最佳答案

你可以使用类似的东西

#include <stdio.h>
#include <stdlib.h>

int main() {
    char string[100];
    int count = 0;

    printf("Enter a string: \n");
    char *pString = fgets(string, sizeof(string), stdin);
    if (pString == NULL) {
        fprintf(stderr, "failure reading from stdin\n");
        exit(1);
    }
    while (*pString != '\0' && *pString != '\n') {
        pString++;
        count++;
    }

    printf("String is %d characters long", count);
    return 0;
}

它使用 fgets 来检查缓冲区的长度。 fgets 还返回用户输入的换行符,因此需要额外检查 '\n'。就像 arvin 提到的评论一样,char 指针也需要在循环中递增。

关于c - 如何使用指针正确地将字符串输入存储到字符数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038132/

相关文章:

arrays - Android Data Binding 与数组的两种方式绑定(bind)

arrays - 在 WooCommerce 3 中序列化购物车内容而不丢失数据

c - 6*6 阵列中可能的最大沙漏总和

c - YACC 未从后继节点获取值

javascript - Javascript 中的迷宫生成器未捕获类型错误

javascript 检查值是否至少有 2 个或更多单词

c中的字符数组消隐

mysql SELECT 哪里喜欢和喜欢

我可以用全 0 初始化数组数组吗?

c - 在 C 中使用特定值初始化动态分配的数组