Trying to convert int to string

It is quite clear from the code below that I am trying to convert an int to a string.

#include <sstream>
#include <string>
#include <iostream>

int num = 1;
ostringstream convert;
convert << num;
string str = convert.str();

      

However, I am getting the error

Line 7: error: expected constructor, destructor, or type conversion to '<marker

What am I doing wrong? This is basically the same piece of code that everyone recommends converting int to string.

+3


source to share


2 answers


There are two questions here, first you are missing main

so afterwards this code is invalid at the top level (e.g. external main / functions / etc). When you compile your program, the compiler looks for main and then starts executing the code from that point on. There are several things that are allowed before the main one, but this expression is not one of them. The reason is that you are trying to compute something, but the program flow never goes there, so how can the compiler decide when to execute this code? It is important what order that occurs in and before the main one is not defined. This statement is not a side effect, so the error message you posted about is complaining. The compiler looks for the main one, like the one where the code will start executing, so you want to put your code mainly for this reason (I know this is more for this, and it is not 100% accurate, but I thinkthat's a good starting point / heuristic for new programmers to understand better). You might want to read this questionIs main () really the start of a C ++ program?

Second, there is a problem with namespaces. ostringstream

is in namespace std

, try it std::ostringstream

. The situation is string

similar, use for this std::string

.



With these changes, the code will look something like 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;
    return 0;
}

      

+3


source


#include <string>
#include <sstream>      // std::stringstream
#include <iostream>

int main()
{
   int num = 1;
   std::stringstream convert;
   convert << num;
   std::string str = convert.str();
   std::cout << str ;
   return 0;
}

      



+1


source







All Articles