2

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.

4
  • 1
    Don't you have a main() function? (+1 for providing a small code example that allows us to reproduce the error!) Commented Nov 11, 2014 at 17:02
  • Oh balls, that was it. Cheers. Commented Nov 11, 2014 at 17:04
  • 1
    Is there any code that doesn't require main()? Commented Nov 11, 2014 at 17:05
  • Only library code. For an application you need that function. Commented Nov 11, 2014 at 17:05

2 Answers 2

3

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.