简体   繁体   中英

Verification: Is entered - integer number? QT c++

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM