In: Computer Science
How would you call a username in a different function when coding in C?
I have a function that logs a user in, and I would like to say if (username == 'abc'){do function} but everytime I use the 'username' variable in a different function, it says it is an undeclared identifier.
Hello,
You can think of passing the identifier to a function after declaring it. Just assign the username of character string and pass it by value.
Below example would help you to understand and please let me know if you need more details.
void func(char *s){
//make use of the identifier passed from the main function
}
main()
{
char username[] = "USER_NAME";
func(username);
}
Happy Learning!
Adding answer based on your question:
No problem. Let me think of executing it as writable/readable text file in C programming. Just refer the below code snippet and customize accordingly.
int Login(){
char name[20];
printf("Enter UserName: ");
scanf("%s", name);
FILE * fp;
fp = fopen("c:\\temp\\userinfo.txt", "w");
fprintf(fp, name);
fclose (fp);
return 0;
}
int callingfunction() {
FILE *fp;
char str[MAXCHAR];
char* filename = "c:\\temp\\userinfo.txt";
fp = fopen(filename, "r");
if (fp == NULL){
printf("Could not open file %s",filename);
return 1;
}
while (fgets(str, MAXCHAR, fp) != NULL)
printf("%s", str);
// or store this in some other variable and execute your
functionality
fclose(fp);
return 0;
}