function - C - Return value to main -
haven't found answering question, here goes:
i want return integer function main further use, it's add()
function creates list entries in text file. integer want return called error, declared 0 @ beginning of function , changes 1 when condition met (in case, if character other a-z, a-z, - , ' ' found). if condition met, want return error (as 1) main function, otherwise return 0. in main have if statement checks if error 1 print error message , return 1. possible? i've tried few things doesn't work, if initialize error variable 0 in main, shouldn't add function change 1 in case of error condition? don't want use global variables , want implement add function main last resort.
sorry if complete nonsense, beginner.
int add(char line[]) { struct node *newnode = (struct node *) malloc(sizeof(struct node)); struct node *walker = newnode; strcpy(newnode->name, line); int check = 0; int error = 0; while(line[check] != '\n') { if(line[check] == '!') { error = 1; return error; } check++; } . //here creation of list elements . //if functions reaches end, returns error 0 value . }
and main:
int main() { file *fp; char line[33]; int error = 0; fp = fopen("test.txt", "r"); if(!fp) { printf("error."); return 0; } while(fgets(line, 33, fp) != null) { add(line); } fclose(fp); if(error == 1) { printf("error"); return 1; } // ... }
edit: ok, i've made work, , since few people had right solution me, wanted here! don't know if can choose multiple answers correct.
the variables have in add()
, main()
local variables. means values contain cannot used outside respective functions. when add()
returns value, need have variable in main()
collect that. so,
while(fgets(line, 33, fp) != null) { /* here when add returns 1 or 0, value collected * "error" variable of main function */ error = add(line); if( error == 1 ) break ; /* simple :-) */ /* once add() returns, break while loop continue main() instructions ahead */ }
Comments
Post a Comment