简体   繁体   中英

How to pass in variable value in char [] in c++

I have below line of code:

char sPostData[500] = "{\"name\":\"Test Unique Name 1\",\"salary\":\"123456\"}";

where instead of Test Unique Name 1 I want to pass a variable value something like below:

string name = "JOHN";
char sPostData[500] = "{\"name\":" + name + "\",\"salary\":\"123456\"}";

But doing so it gives below error:

Error (active)  E0520   initialization with '{...}' expected for aggregate object   

Error   C2440   'initializing': cannot convert from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'char []'  

How can I resolve this issue and pass in the variable value in between. Thanks

Use some std::string . So something similar to (the quoting is a bit wrong, you'll correct it)

std::string PostData =
  std::string{"{\"name\":"} + name + "\",\"" + salary + "\":\"123456\"}";

Later use PostData.c_str() instead of your sPostData ....

Read also about raw string literals . In your case, they are helpful.

Learn also more about std::ostringstream . For example:

std::ostringstream os;
os << "{\"name\":" << name << "\",\"" << salary
   << "\":\" << pay << "}" << std::endl;
std::string PostData = os.str();

But you really should use some good JSON library , like jsoncpp . You probably should look into its 2 nd example .

If you are coding something related to HTTP , learn more about that protocol, then consider using some HTTP client library like libcurl and/or HTTP server library like libonion or Wt or a framework like POCO or Qt .

BTW, IMHO, a Linux distribution is a better development platform (even for cross-compilation) than Windows is in your particular case.... (good UTF-8 support, good HTTP support, good JSON support) and many embedded hardware (eg RaspBerry PI ) are Linux friendly.

See also http://utf8everywhere.org/

Beware that C++ is a very difficult language. See this and read http://norvig.com/21-days.html for a more general insight.

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