请教:要求输入数字,如果输入字符,则重新输入.

nnh 2006-07-29 03:44:23
如题.

谢谢.
...全文
337 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dong 2006-07-29
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

bool alldigit(char* str)
{
while(*str != '\0')
{
if(isdigit(*str) == false)
return false;
str++;
}
return true;
}

int main()
{
int ch;
char str[10];
while (cin>>str)
{
if(alldigit(str))
{
ch = atoi(str);
break;
}
else
cout << "请输入数字:";
}

cout << ch << endl;
system("pause");
return 0;
}
Ah_dong 2006-07-29
  • 打赏
  • 举报
回复




int n;
while(n!=EOF)
{
cin>>n;
if(!(n>=0 && n<=9))
continue;
//operations
}
nnh 2006-07-29
  • 打赏
  • 举报
回复
呵呵,问题根本就没解决嘛.

哎.伤心呀....
chenhu_doc 2006-07-29
  • 打赏
  • 举报
回复
信息已经给全了,点到为止啦!
nnh 2006-07-29
  • 打赏
  • 举报
回复
我想用如下的代码可以实现吗?

#include <iostream>
using namespace std;
int main()
{
int ch;

while (条件)
{
cout << "请输入数字:";
}

cout << ch << endl;
system("pause");
return 0;
}
nnh 2006-07-29
  • 打赏
  • 举报
回复
chenhu_doc,你后边给的那个已知ch为数字,可是用户输入的不一定是数字呀?这怎么对它进行判断呢?
nnh 2006-07-29
  • 打赏
  • 举报
回复
那我要对它进行判断,用while来做呢?
chenhu_doc 2006-07-29
  • 打赏
  • 举报
回复
恩,

#include<iostream>
#include<string>
using namespace std;


void main()
{
char *a = "123";
int ch = atof(a); //这个函数就可以转换了!
cout << ch <<endl;
}
nnh 2006-07-29
  • 打赏
  • 举报
回复
chenhu_doc,这我知道,可我就想用 int ch,可是不太会写呀.麻烦大家帮忙了.
chenhu_doc 2006-07-29
  • 打赏
  • 举报
回复
而且isdigit(ch)在c++ 只能对字符进行判断,所以对字符串输入的完整分析判断要做循环。。

不然,检验过程就会出错。。。
chenhu_doc 2006-07-29
  • 打赏
  • 举报
回复
char ch; // 很明显,只能接受一个字符,所以要写成string类型的!
nnh 2006-07-29
  • 打赏
  • 举报
回复
谢谢上边的代码.

我写了如下的代码:
#include <iostream>
using namespace std;
int main()
{
char ch;
cin >> ch;
while (!isdigit(ch))
{
cout << "请输入数字:";
cin >> ch;
}

cout << ch << endl;
system("pause");
return 0;
}

代码输入100,可只显示1.

我想要的就是如果输入非数字,则重新提示输入,否则输出全部内容.

如输入202,则会显示202


chenhu_doc 2006-07-29
  • 打赏
  • 举报
回复
练笔居然这么失败,重来。。。。
chenhu_doc 2006-07-29
  • 打赏
  • 举报
回复
#include <iostream>
#include <string>
using namespace std;



int main()
{
string a;
do
{
cin >> a;
for( string::size_type index =0; index < a.size(); ++index )
{
if( !isdigit(a.at( index )))
{
cout << "error input.. input again."<<endl;
break;
}
break;
}
break;
}while( 1 );
system("PAUSE");
return 0;

}
Dong 2006-07-29
  • 打赏
  • 举报
回复
你不是已经解决了吗?

char str[100];
while(!isdigit(gets(str)))
{
printf("not digit,input again\n");
}

64,647

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧