0

Please help me with optimize the function of checking the entered value. Function returns true and sent value using link, if entered - integer, or returns false if entered char, string(empty). I think there are 2 ways to speed increase: eliminate the use of std::string or eliminate the use of QString.

bool tryRead(int &v)
{
    QString s;
    string s1;
    cin >> s1;
    s = QString::fromStdString(s1);
    if (s.isEmpty())
    {
        cout << "Error! You entered empty string";
        return false;
    }
    bool isNumber = true;
    v = ((s.toInt(&isNumber)));
    if(isNumber == false)
        return false;
    return true;
}
punksta
  • 2,738
  • 3
  • 23
  • 41
  • 2
    Perhaps not relevant, but in what situation would you need to optimize this? There's no way that this is the bottleneck of an application if you're actually taking user input. – vroomfondel Nov 17 '13 at 06:26
  • Increasing speed. Reducing the number of calls to the variable. Now I called 2 times: s=QString::fromStdString(s1); v=((s.toInt(&isNumber))); I think if read QString or check string will faster. – punksta Nov 17 '13 at 06:28
  • 3
    How fast do you expect the user to type to have this make a difference? – Frank Osterfeld Nov 17 '13 at 08:40
  • 1
    Replacing the last 3 lines with `return isNumber;` will help me sleep at night. Also using a `QIntValidator` is the preferred 'Qt' of way of doing this (https://qt-project.org/doc/qt-5.1/qtgui/qintvalidator.html). – cmannett85 Nov 17 '13 at 10:50
  • You can read from cin to QString directly as described [here](http://stackoverflow.com/a/3018745/344347). – Pavel Strakhov Nov 17 '13 at 15:22

2 Answers2

0

This is what iostream operators are for. A minimal implementation would be:

bool tryRead(int &v){
    cin >> v;
    return cin.good();
}

Depending on what you actually want to accomplish you may want to add some additional sanity checking, error handling and cleanup of cin.

pentadecagon
  • 4,717
  • 2
  • 18
  • 26
0

Instead of using cin and cout you can use QTextStream.

QTextStream cin(stdin), cout(stdout);
int myint;
cin >> myint;
if(cin.status() != QTextStream::Ok)
    cout << "It is not an integer!" << endl;

After detecting the error make sure to call QTextStream::resetStatus() to clean the error flags.

Nazar554
  • 4,105
  • 3
  • 27
  • 38