首页 > 解决方案 > 传递字符串时为空

问题描述

我得到了这个输出“COVIC19 ΓÇô 社区访问的医院(空)ΓÇô 报告”我试图从函数 readHospital() 中打印出医院的名称,但我得到的输出只是这些看起来很奇怪的文本。很抱歉,我对编码很陌生。

#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);
}

标签: c

解决方案


我已经更改了您的代码,您在代码中使用的 readHospital 函数不是从用户读取输入字符串并返回它的正确函数。相反,您可以使用我编写的 readNewString 函数。

#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);
}

推荐阅读