0

May be i am getting a trouble with my question, I tried to know how can my code run like this...What is my trouble, please help me here is my code:

string arr[3][4];
arr[1][0] = "34234";
printf("%s",arr[1][0]);

But my output is %#$ ( something like this). Please help me, thanks you very much.

3
  • 1
    string ?? user-defined??, printf("%s",arr[1]) Commented Jun 25, 2013 at 10:07
  • Don't you even get a warning for this? Are you compiling without warnings enabled? Commented Jun 25, 2013 at 10:08
  • you should print using std::cout << arr[1][0] << std::endl; Commented Jun 25, 2013 at 10:09

3 Answers 3

5

It's because the printf function knows nothing about the C++ std::string class. It's there because it's part of the C standard library.

To get a C-style string that you can use in e.g. printf you have to use the c_str method:

printf("%s", arr[1][0].c_str());

But what you really should do is to learn how to use the native C++ stream output:

std::cout << arr[1][0];

PS. Instead of old C-style arrays, you should also look into the C++ standard containers, like std::vector and std::array.

Sign up to request clarification or add additional context in comments.

Comments

2

printf is a C function and know nothing about types such as std::string. You can either use the type safe std::cout, from the <iostream> header:

std::cout << arr[1][0];

or, if you really need to call printf (and give up on type safety), call std::string::c_str(), which returns a const char* to the null-terminated string held by an std::string. printf will understand this.

printf("%s",arr[1][0].c_str());

Comments

1

use std::cout instead of printf with std::string, because C function printf has no view of std::string.

#include <iostream>
std::cout << arr[1][0];

To make your code work, you need to get C char array by calling std::string::c_str function

printf("%s",arr[1][0].c_str());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.