【问题标题】:Getting input from user till he enters a number从用户那里获取输入,直到他输入一个数字
【发布时间】:2017-01-12 19:15:11
【问题描述】:

我必须从用户那里得到字符输入,直到他输入一个数字。我还需要用户最后输入的号码。

#include <iostream>
using namespace std;
int fun() {
    char c;
    while(1) {
        if(cin>>c == 1) {  //To check if we are still getting input
            if(isdigit(c)) { //If a number is found return to the main function
                return c-48;  //Char converted to Int
            }
        }
        else {
            break;
        }
    }
    return c-48;
}

int main() {
    int a = fun();
    cout<<a;
    return 0;
}

现在对于像ahd qer 12 32 这样的输入,它会给出1 的输出,我知道它会给出。我想要输出的是12。怎么做?您也可以对主要功能进行一些更改。我最终想要存储在变量a 中的数字。

解决方案

    #include <iostream>
    using namespace std;

    int fun() {
        string c;
        while(cin>>c) {
            if(isdigit(c[0]))
                return stoi(c);
        }
    }

    int main() {
        int a = fun();
        cout<<a<<" ";
        return 0;
    }

【问题讨论】:

  • @Gyanshu 特殊字符怎么样(例如#/$/etc..)?如果您想知道字符是否代表数字,为什么不至少使用isdigit
  • 至少在 C 中将(签名)字符传递给 isdigit 是未定义的行为(并且您需要 #include &lt;ctype.h&gt;)。
  • 好的,我会用 isdigit 替换它。但这也只给了我数字的第一位。有没有办法得到整数?
  • cfun 末尾可能未初始化。
  • 题外话:您可能会发现将return c-48; 替换为return c-'0'; 会使您的代码更易于阅读。

标签: c++ char int


【解决方案1】:

完成! 信用:@AlgirdasPreidžius

    #include <iostream>
    using namespace std;

    int fun() {
        string c;
        while(cin>>c) {
            if(isdigit(c[0]))
                return stoi(c);
        }
    }

    int main() {
        int a = fun();
        cout<<a<<" ";
        return 0;
    }

【讨论】:

  • 我的输入不包含这样的字符串。
  • 它只包含数字或字符串
  • 此外,对于您所说的输入,我将扫描整个字符串。
猜你喜欢
  • 2020-10-29
  • 2019-06-19
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-18
相关资源
最近更新 更多