MUFAMIN
MUFAMIN

Reputation: 13

Null When Passing String

I got this output "Hospital (null) ΓÇô Report for COVIC19 ΓÇô Community Visit" I'm trying to printout the name of the hospital from the function readHospital() but all I got for the output is these weird looking text. So sorry I'm very new to coding.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>

char readHospital();
void intro(char a);


int main() {

char hospital_name;

hospital_name = readHospital();
intro(hospital_name);

}


char readHospital() {

char a[100];
printf("Enter Hospital Name: ");
fgets(a, 100, stdin);
return a;
}

void intro(char hospital_name) {
printf("Hospital %s  – Report for COVIC19 – Community Visit", hospital_name);
}

Upvotes: 0

Views: 40

Answers (2)

Erfan Taghvaei
Erfan Taghvaei

Reputation: 162

I've changed your code, The readHospital function that you are using in your code is not a correct function for reading the input string from the user and returning it. Instead, you can use the readNewString function that I've written.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>

char * readNewString();
void intro(char a[100]);


int main() {

char * hospital_name;

hospital_name = readNewString();
intro(hospital_name);

}


char *readNewString(void) {
char buffer[1024];
if (!fgets(buffer, sizeof buffer, stdin)) {
    return NULL; // read failed, e.g., EOF
}
int len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
    buffer[--len] = '\0'; // remove the newline
    // You may also wish to remove trailing and/or leading whitespace
} else {
    // Invalid input
    //
    // Depending on the context you may wish to e.g.,
    // consume input until newline/EOF or abort.
}
char *str = malloc(len + 1);
if (!str) {
    return NULL; // out of memory (unlikely)
}
return strcpy(str, buffer); // or use `memcpy` but then be careful with length
}



void intro(char hospital_name[100]) {
printf("Hospital %s  – Report for COVIC19 – Community Visit", hospital_name);
}

Upvotes: 2

snatchysquid
snatchysquid

Reputation: 1352

Please note that hospital_name is of char type and you return a string, char list char*

Upvotes: 0

Related Questions