Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a string in C++ [closed]

Tags:

c++

string

printf

I tried this, but it didn't work.

#include <string> string someString("This is a string."); printf("%s\n", someString); 
like image 252
node ninja Avatar asked Mar 16 '11 07:03

node ninja


People also ask

What is %s in C?

%s is for string %d is for decimal (or int) %c is for character.

How do you print strings in C?

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);

How do I print a string with spaces?

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.

How is string ended in C?

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.


2 Answers

#include <iostream> std::cout << someString << "\n"; 

or

printf("%s\n",someString.c_str()); 
like image 71
GWW Avatar answered Oct 05 '22 07:10

GWW


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::.

like image 20
ThiefMaster Avatar answered Oct 05 '22 09:10

ThiefMaster