【发布时间】: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 <ctype.h>)。 -
好的,我会用
isdigit替换它。但这也只给了我数字的第一位。有没有办法得到整数? -
c在fun末尾可能未初始化。 -
题外话:您可能会发现将
return c-48;替换为return c-'0';会使您的代码更易于阅读。