I tried this, but it didn't work.
#include <string> string someString("This is a string."); printf("%s\n", someString);
%s is for string %d is for decimal (or int) %c is for character.
using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);
Program Explanation Get a String using fgets() function. Str -> reads the string and stores it in str. 50 -> reads maximum of 50 characters stdin-> reads character from keyboard using for loop print all characters one by one. "%c " in printf prints character with space.
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
#include <iostream> std::cout << someString << "\n";
or
printf("%s\n",someString.c_str());
You need to access the underlying buffer:
printf("%s\n", someString.c_str());
Or better use cout << someString << endl;
(you need to #include <iostream>
to use cout
)
Additionally you might want to import the std
namespace using using namespace std;
or prefix both string
and cout
with std::
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With