c++ - Attempting to convert int to string -



c++ - Attempting to convert int to string -

it's quite clear code below attempting convert int string.

#include <sstream> #include <string> #include <iostream> int num = 1; ostringstream convert; convert << num; string str = convert.str();

however, error message

line 7: error: expected constructor, destructor, or type conversion before '<<' token

what doing wrong? same snippet of code recommends convert int string.

there's 2 issues here, first missing main subsequently code not valid @ top-level (eg outside main/functions/etc). when compile programme compiler looks main starts executing code point onwards. there's few things allowed before main look not 1 of them. reason because trying compute programme flow never goes there, how can compiler decide when execute code? matters order happens in , before main order not defined. statement not side-effect free that's error message posted complaining about. compiler looks main that's code start executing want set code in main reason (i know more , it's not 100% accurate think starting point/heuristic new programmers improve understanding). might want read question is main() start of c++ program?

secondly there's issue namespaces. ostringstream in std namespace, seek std::ostringstream instead. situation string similar, utilize std::string that.

with these changes code end looking this:

int main(){ int num = 1; std::ostringstream convert; convert << num; //this isn't allowed outside of main std::string str = convert.str(); std::cout << str; homecoming 0; }

c++

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -