[英]function to read a string and get the length - C
我在編寫C函數時遇到問題,該函數從STDIN讀取字符串,並返回所述字符串的長度...建議?
因此,只需使用C標准庫中的strlen:
#include <string.h>
因此,strlen()函數可用。 您只需要傳遞一個char指針,它將返回字符串長度:
size_t length = strlen( myStr );
請注意,size_t是整數類型。
順便說一句,如果您不了解此功能,則應該深入研究C庫,並了解它提供的基本功能。
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.