c - Values always do not tally -
i'm relatively new c programming , trying code program reads in user's marks , assign grade mark inputted. have used getline()
function acquire user input. below code.
# include <stdio.h> # include <stdlib.h> # include <string.h> # include <ctype.h> int getmark(); void display(char grade); char convert(int mark); int getmark() { { int marks; char * buffer; char characters; size_t bufsize = 16; buffer = (char *)malloc(bufsize * sizeof(char)); if( buffer == null) { perror("unable allocate buffer"); exit(1); } printf("enter score (0 - 100)\nor press enter key quit ==> "); characters = getline(&buffer, & bufsize, stdin); int i; long check; (i = 0; < sizeof(buffer); i++) { if (buffer[i] == '\n' && != 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 integer.\n"); continue; } if (marks >= 0 && marks <= 100) { return marks; } else { printf("sorry, marks can between 0 100.\n"); continue; } } while (1); } void display(char grade) { printf("the grade input score %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; (;;) { marks = getmark(); if (marks == -1) { break; } display(convert(marks)); } return 0; }
when press enter, program exits, expected. however, when integer entered, example 12
, output please enter integer.
can me on this? thanks!
char * buffer; ... (i = 0; < sizeof(buffer); i++) { if (buffer[i] == '\n' && != 0) {
sizeof(buffer)
returns size of pointer char (4 or 8 bytes depending on architecture), not length of string, in consequence, reading outside of bounds of array when 12
entered.
change strlen()
or better yet, use result of getline
:
on success, getline() , getdelim() return number of characters read, including delimiter character, not including terminating null byte ('\0').
Comments
Post a Comment