需要帮助创建一个 returns 您输入的字符串大小的函数

Need help creating a function that returns the size of the string you type in

所以我做的练习题要求写一个完整的C程序,从键盘输入一行文字,计算输入字符串的大小。您的程序应该使用函数 stringLength() 来计算和 returns 给定字符串的大小。函数具有以下 prototype:size_t stringLength(const char* sPtr);

以下是我所拥有的,但我仍在学习中。我假设它也要求实现指针,而且在指针方面我非常固执。该功能基本上就是我卡住的地方,有什么提示或指示吗?

#include <stdio.h>

// prototype
size_t stringLength(const char* sPtr) {

    int* str = &sPtr;
    return sizeof(str);
}

int main() {

char* s[100]; //input string

puts("Enter a string");
fgets(s, 99, stdin);

printf("According to stringLength, the length is: %d\n", stringLength(&s));

return 0;
}
  • 您应该使用 char 的数组,而不是 char* 的数组来存储字符串。
  • sizeof 用于确定类型的大小。您应该使用 strlen() 来确定字符串的长度。
  • 固定 s 的类型后,将 s 而不是 &s 传递给 stringLength 以匹配参数的数据类型。
  • %d 用于打印 int。您应该使用 %zu 打印 size_t.

试试这个:

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

// prototype
size_t stringLength(const char* sPtr) {

    return strlen(sPtr);
}

int main() {

    char s[100]; //input string

    puts("Enter a string");
    fgets(s, 99, stdin);

    printf("According to stringLength, the length is: %zu\n", stringLength(s));

    return 0;
}