Jason Rogers
Jason Rogers

Reputation: 29

Attempting to convert int to string

It's quite clear from the code below that I am attempting 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 get the error message

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

What I am doing wrong? This is basically the same snippet of code that everyone recommends to convert an int to a string.

Upvotes: 2

Views: 113

Answers (2)

shuttle87
shuttle87

Reputation: 15934

There's 2 issues here, first you are missing main so subsequently this code is not valid at the top-level (eg outside main/functions/etc). When you compile your program the compiler looks for main then starts executing the code from that point onwards. There's a few things that are allowed before main but this expression is not one of them. The reason is because you are trying to compute something but the program flow never actually goes there, so how can the compiler decide when to execute that code? It matters what order that happens in and before main that order is not defined. That statement is not side-effect free so that's what the error message you posted is complaining about. The compiler looks for main as that's where code will start executing from so you want to put your code in main for that reason (I know this is more to this and it's not 100% accurate but I think this is a good starting point/heuristic for new programmers to get better understanding). You might want to read this question Is main() really start of a C++ program?

Secondly there's an issue with namespaces. ostringstream is in the std namespace, try std::ostringstream instead. The situation with string is similar, use std::string for that.

With these changes the code will end up looking 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;
}

Upvotes: 3

Emadpres
Emadpres

Reputation: 3747

#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;
}

Upvotes: 1

Related Questions