如何在我的C代码中返回一个字符串?

我是C初学者,这是我的C代码:

#include  #include  main() { printf("Hello world !\n"); return 'sss'; } 

这将显示错误,

那么如何在C代码中返回一个字符串?

如果你想从函数(main除外)返回一个字符串,你应该这样做。

 #include  const char * getString(); int main() { printf("hello world\n"); printf("%s\n", getString()); return 0; } const char * getString() { const char *x = "abcstring"; return x; } 

神奇的关键词是static ,即使在函数结束后也会保留字符串的内存内容。 (您可以将其视为扩展变量的范围。)

此代码每次占用一个字符,然后将它们连接成一个字符串并将其保存到文件中:

 #include  #include  char* strbsmallah () { static char input[50]; char position =0, letter; scanf("%c",&letter); while (letter != '~') { // press '~' to end your text input [position]=letter; ++position; scanf("%c",&letter); } input[position]='\0'; char *y; y = (char*) &input; //printf("%s\n ",y); return y; } int main() { printf("\n"); FILE *fp; fp = fopen("bsmallah.txt", "w+"); fprintf(fp, strbsmallah()); while (!_kbhit()); return 0; } 

你可以用simplar来扫描这个。 换一种说法:

 void foo(char **value_to_return) { *value_to_return = malloc(256); // store 256 chars strcpy(*value_to_return, "deposited string"); } int main() { char *deposit; foo(&deposit); printf("%s", deposit); return 0; } 

可悲的是,没有办法做到这一点。

您可以在c程序的末尾添加一些内容,例如:

 int main() { int err = 0; // 0 is "success" is most c programs printf("hello world!\n"); switch( err ) { case 0: printf("program shutdown succesfully!\n"); break; case 1: printf("we had an issue somewhere. please fix your input data\n"); break; //case 2, 3, etc... }; return err; } 

你没有返回一个字符串。 应用程序以整数退出代码退出。

通常,以0返回退出将始终显示您的应用程序退出而没有错误/已完成。 返回0以外的整数表示您的应用程序exception退出。

您可以抛出exception并使用调用堆栈中较高的日志记录方法来处理它,或者您可以返回0以外的其他内容,并确保在发布说明中记录了每个错误整数的含义。

您可能可以使用环境变量。 不过不确定。