我正在尝试在C中创建一个函数,它将打印一个作为参数的字符串。这在C中甚至可能吗?
我的头文件中有类似的内容,但字符串不是有效的标识符。我知道C中没有字符串,但是string.h类是什么?
#include <string.h>
#ifndef _NEWMAIN_H
#define _NEWMAIN_H
#ifdef __cplusplus
extern "C" {
#endif
void print (string message){ //this is where i need help
printf("%s", message);
}
#ifdef __cplusplus
}
#endif
#endif /* _NEWMAIN_H */
答案 0 :(得分:5)
在C中,没有原生string
类型。
C将字符串作为以null结尾的char
数组处理。
例如:
char* string = "this is a string";
string.h
存在于C字符串上执行字符串操作函数,类型为char*
。
使用printf
打印字符串时,会传递char*
的变量:
char* string_to_print = "Hello";
printf("%s", string_to_print);
有关C中字符串的更多信息,Wikipedia page on C strings将是一个良好的开端。
答案 1 :(得分:3)
void print (const char* message) {
printf("%s", message);
}
答案 2 :(得分:1)
在简单地考虑之后,对于你的家庭作业,即替换printf,你会想要使用其他人指出的char *
,并使用fwrite来进行stdout。
您可以查看相关问题 C/C++ best way to send a number of bytes to stdout
答案 3 :(得分:0)
C中没有字符串,因为C中没有类。string.h提供了在C中处理字符串文本操作的例程,使用指向char的指针。
你想要重写这个:
void print(const char* message) {
printf(message); // You don't need the formatting, since you're only passing through the string
}
话虽这么说,但与直接调用printf并没有什么不同。