我对C编程比较陌生,我正在尝试编写一个读取用户标记的程序,并为输入的标记分配一个等级。
我使用getline()
函数来获取用户输入。以下是我的代码。
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
int getMark();
void display(char grade);
char convert(int mark);
int getMark() {
do {
int marks;
char * buffer;
char characters;
size_t bufsize = 16;
buffer = (char *)malloc(bufsize * sizeof(char));
if( buffer == NULL) {
perror("Unable to allocate buffer");
exit(1);
}
printf("Enter the score (0 - 100)\nOr just press the enter key to quit ==> ");
characters = getline(&buffer, & bufsize, stdin);
int i;
long check;
for (i = 0; i < sizeof(buffer); i++) {
if (buffer[i] == '\n' && i != 0) {
buffer[i] = '\0';
}
if (isdigit(buffer[i]) || buffer[i] == '\0') {
check++;
}
}
if (buffer[0] == '\n') {
return -1;
} else if (check == strlen(buffer) - 1) {
marks = atoi(buffer);
} else {
printf("Please enter an integer.\n");
continue;
}
if (marks >= 0 && marks <= 100) {
return marks;
} else {
printf("Sorry, your marks can only be between 0 to 100.\n");
continue;
}
} while (1);
}
void display(char grade) {
printf("The grade for the input score is %c \n", grade);
}
char convert(int mark) {
mark /= 10;
char grade;
switch(mark) {
case 0:
case 1:
case 2:
case 3:
grade = 'F';
break;
case 4:
grade = 'E';
break;
case 5:
grade = 'D';
break;
case 6:
grade = 'C';
break;
case 7:
grade = 'B';
break;
case 8:
case 9:
case 10:
grade = 'A';
}
return grade;
}
int main() {
int marks;
for (;;) {
marks = getMark();
if (marks == -1) {
break;
}
display(convert(marks));
}
return 0;
}
当我按 Enter 时,程序将按预期退出。
但是,输入整数时,例如12
,输出将始终为Please enter an integer.
任何人都可以帮我这个吗?谢谢!
答案 0 :(得分:0)
char * buffer;
...
for (i = 0; i < sizeof(buffer); i++) {
if (buffer[i] == '\n' && i != 0) {
sizeof(buffer)
返回指向char 的指针的大小(4或8个字节,具体取决于体系结构),而不是字符串的长度,因此,您正在读取输入12
时数组的边界。
更改为strlen()
或更好,使用getline
的结果:
成功时,getline()和getdelim()返回字符数 读取,包括分隔符,但不包括 终止空字节(&#39; \ 0&#39;)。