#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/