开发者

function to read a string and get the length - C

开发者 https://www.devze.com 2023-03-06 07:55 出处:网络
I\'m having issues writing a C function that reads a string from STDIN, and returns the length of said st开发者_StackOverflowring... Suggestions?So, simply use strlen from the C standard library:

I'm having issues writing a C function that reads a string from STDIN, and returns the length of said st开发者_StackOverflowring... Suggestions?


So, simply use strlen from the C standard library:

#include <string.h>

So the strlen() function is available. You just need to pass a char pointer, and it will return the string length:

size_t length = strlen( myStr );

Note that size_t is an integral type.

By the way, if you don't know about this function, you should really dig into the C library, and lear about the basic functions it provides.


#include <stdio.h>
#include <stdlib.h>  // not totally necessary just for EXIT_SUCCESS
#include <string.h>

int main(int argc, char* argv[]) {

    // check number of params
    if (argc != 2) {
        // argv[0] is name of exe
        printf("usage: %s string", argv[0]);

    // check length of first command line parameter
    } else {
                    // strlen does the counting work for you
        unsigned int length = strlen(argv[1]);

        printf("Length is %d\n", length);
    }

    return EXIT_SUCCESS;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号