Reputation: 27629
I am trying to make a function in C that will print a string taken as a parameter. Is this even possible in C?
I have something like this in my header file, but string is not a valid identifier. I understand there are no strings in C, but what's the string.h class for?
#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 */
Upvotes: 1
Views: 6405
Reputation: 41848
After thinking about it briefly, for your homework assignment, which is to replace printf, you will want to use char *
as pointed out by others, and use fwrite to stdout.
For a related question you can look at C/C++ best way to send a number of bytes to stdout
Upvotes: 1
Reputation: 564831
There are no strings in C, since there are no classes in C. string.h provides the routines for handling string text manipulation in C, using pointers to char.
You'll want to rewrite this like:
void print(const char* message) {
printf(message); // You don't need the formatting, since you're only passing through the string
}
That being said, it's not really any different than just calling printf directly.
Upvotes: 0
Reputation: 161022
In C, there is no native string
type.
C handles strings as a null-terminated char
array.
For example:
char* string = "this is a string";
The string.h
exists to perform string manipulation functions on C strings, which are of type char*
.
When printing a string using printf
, one would pass in a variable of char*
:
char* string_to_print = "Hello";
printf("%s", string_to_print);
For more information on strings in C, the Wikipedia page on C strings would be a good start.
Upvotes: 5
Reputation: 7705
void print (const char* message) {
printf("%s", message);
}
Upvotes: 3