How to print a string in the C language.
There are several ways to output a string in the C language.
- Format strings for output using the printf function.
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("%s\n", str);
return 0;
}
- Use the puts function to print a string and automatically add a new line.
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
puts(str);
return 0;
}
- Output the string to the specified file stream using the fputs function.
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
fputs(str, stdout);
return 0;
}
- Output the string character by character using the putchar or fputc function.
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int i = 0;
while(str[i] != '\0') {
putchar(str[i]);
i++;
}
return 0;
}
These methods can all be used to output strings, the specific choice depending on the needs and the usage scenario.