我的任务是计算随机单词中的字母数量,直到输入“End”。我不允许使用 strlen();功能。这是我到目前为止的解决方案:
#include <stdio.h>
#include <string.h>
int stringLength(char string[]){
unsigned int length = sizeof(*string) / sizeof(char);
return length;
}
int main(){
char input[40];
while (strcmp(input, "End") != 0) {
printf("Please enter characters.\n");
scanf("%s", &input[0]);
while (getchar() != '\n');
printf("You've entered the following %s. Your input has a length of %d characters.\n", input, stringLength(input));
}
}
stringLength 值不正确。我做错了什么?
最佳答案
%n
说明符也可用于捕获字符数。
使用 %39s
将防止向数组 input[40]
写入过多字符。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( void)
{
char input[40] = {'\0'};
int count = 0;
do {
printf("Please enter characters or End to quit.\n");
scanf("%39s%n", input, &count);
while (getchar() != '\n');
printf("You've entered the following %s. Your input has a length of %d characters.\n", input, count);
} while (strcmp(input, "End") != 0);
return 0;
}
编辑以纠正@chux指出的缺陷。
使用 "%n
记录前导空格并使用 %n"
记录总字符数,这应该记录前导空格数和解析的总字符数。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
char input[40] = {'\0'};
int count = 0;
int leading = 0;
do {
printf("Please enter characters. Enter End to quit.\n");
if ( ( scanf(" %n%39s%n", &leading, input, &count)) != 1) {
break;
}
while (getchar() != '\n');
printf("You've entered %s, with a length of %d characters.\n", input, count - leading);
} while (strcmp(input, "End") != 0);
return 0;
}
编辑stringLength()
函数以返回长度
int stringLength(char string[]){
unsigned int length = 0;
while ( string[length]) {// true until string[length] is '\0'
length++;
}
return length;
}
关于c - 如何在不使用strlen的情况下计算字符串的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533177/