Integer for String

4

In QT Creator 5, how do I convert Integer to string? In Visual Studio 2012 there was the command:

std::to_string(10);

But it does not work on QT. I tried:

#include <QCoreApplication>
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);
  std::cout << std::to_string(10);
  return a.exec();
}

The error is this:

G:\PROJETOS\CPP\untitled1\main.cpp:7: error: 'to_string' is not a member of 'std'
   std::cout << std::to_string(10);
                ^
    
asked by anonymous 24.12.2014 / 14:26

3 answers

3

I just ran a test and it worked:

#include <string>

int main() {
  std::string s = std::to_string(10);
}

If it does not work, you're probably using an old compiler. I strongly advise you to update it.

If you want to break a branch temporarily you can use a function of your own:

#include<sstream>
template <typename T> std::string to_string(T value) {
  //create an output string stream
  std::ostringstream os;
  //throw the value into the string stream
  os << value ;
  //convert the string stream into a string and return
  return os.str() ;
}

Source: answer in SO .

Compile along with your application and you will have no problems.

    
24.12.2014 / 14:43
3

To use std::to_string you need C++11

However you may be able to do otherwise using sstream

An example

#include <iostream>
#include <sstream>

int main(int argc, char *argv[])
{
    std::stringstream ss;
    ss << 10;

    std::string minhanovastring = ss.str();
    std::cout << minhanovastring;

    return a.exec();
}
    
24.12.2014 / 15:43
2

Use the class's own function: QString::number(); . Shown as follows:

#include <QTextStream>
#include <QString>

QTextStream out(stdout);

int main(){

    int num = 10;

    QString s = QString::number(num);

    out << s << endl;

    return 0;
}

QString is better at integrating with Qt, and has more features. It also becomes better at different encodings. The only drawback is that for non-Qt projects, std::string is the default.

    
30.01.2015 / 20:39