简体   繁体   中英

how to assign variable to element of string array

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM