【发布时间】:2014-04-23 11:06:12
【问题描述】:
我正在编写一个具有 2 个函数和一个主函数的 C 程序。第一个函数读取并存储字符(更多描述包含在下面的评论中)。我不确定我是否正确终止了字符串(使用 0)??
提前感谢您的帮助!
#include <stdio.h>
#define MAX 20
/* reads a line from the keyboard and stores the characters in the array str.
If the user enters more than max characters, it returns -1. Function should terminate
the char array with a NULL (or 0) */
int getline(char str[], int max){
char c, i;
while((c = getchar()) != '\n'){
str[i] = c;
i = i + 1;
}
str[i] = '\0';
if (i < MAX)
return 0;
else
return -1;
}
/* calculates and returns the length of the array passed to it */
int strlen(char str[]){
int i = 0;
while(str[i] != NULL)
i++;
return i;
}
main(){
char str[MAX];
printf("Please Enter a String less than 20 characters:\n");
if((getline(str, MAX)) == 0)
printf("Length of ‘%s’ = %d", str, (strlen(str)));
else
printf("You Entered more than 20 Characters!");
}
【问题讨论】:
-
str[i] != NULL可能会起作用,但它是不正确的。NULL是一个空 pointer 常量。你想要str[i] != '\0'
标签: c function return printf getline