仅从用户输入中读取数字

Only read numbers out of users input

我正在尝试编写一个只从用户输入中读取四个整数的函数,如下所示:ewzge242jfdsiii23 所以它应该只保存 2422。 这是我的代码,如果我让它计算数字,它只会给我一些奇怪的输出。 你能不能看到我的错误并解释为什么我不能像我那样做以及我可以做些什么?非常感谢!

    int readnumber ( ) {

   char kar, ont_kar, ont_ont_kar;
      int number;
    while (kar != '\n' ){
             cin.get (kar);
        if (kar >= '0' && kar <= '9') {
            old_kar=kar;
            old_kar = old_kar*10 + (kar - '0');
            old_old_kar = old_kar ;
        } //if
    } //while
    if (old_kar < 9999) {

        number=old_kar;
    }//if
    else {

        number=old_old_kar;
    }//else

}//readnumber

这看起来太复杂了,为什么需要那么多变量?

old_karold_old_kar 也打错了。功能没有return,应该是主要问题

这是一个简单的示例:

unsigned readnumber(int number_of_chars) {
    char ch;
    unsigned number = 0;
    while (number_of_chars > 0) {
        std::cin.get(ch);
        if ('\n' == ch)
            break;  // Stop on new line
        if (ch < '0' or ch > '9')
            continue; // Skip non-digits
        --number_of_chars; // One digit processed
        number = number * 10 + ch - '0'; // And added to the result
    }
    return number;
}

这里是没有 breakcontinue 的完整版本:

#include <iostream>     // std::cin, std::cout
#include <fstream>      // std::ifstream

using namespace std;

int readnumber(int number_of_chars) {
    char ch;
    int number = 0;
    while (number_of_chars > 0) {
        std::cin.get(ch);
        if ('\n' == ch)
            return number;
        if (ch >= '0' and ch <= '9') {
            --number_of_chars;
            number = number * 10 + ch - '0';
        }
    }
    return number;
}


int main() {
    int n = readnumber(4);
    cout << "You entered: " << n << endl;
    return 0;
}

注意:始终在打开所有警告的情况下进行编译,这将为您节省大量时间。