C语言高分 输入任意字符串,取其中数字及正负号输出

MENU:
(1)输入字符串:
(StringConvertibleToInteger() function)
(2)转换成int:
(convertToInt() function)
(3)显示结果
(4)退出

Sample Output:

Entered String Displayed Result
126 126
CIS 2xx 无效数据/ 重新输入数据
2xx CIS 无效数据/ 重新输入数据
- 126 -126
+ 126 126
126 45 无效数据/ 重新输入数据
126.45 无效数据/ 重新输入数据
不对啊

题目要求是将输入的有效字符串转换成有符号的长整形输出,
有效字符串标准格式为[sssss][+][sssss]ddddd[sssss]或[sssss][-][sssss]ddddd[sssss]

s=空格,d=数字,“[]”内的内容是可选的,既可以存在也可以不存在,但d一定要连续存在,正负号必须在数字前

以下"_"代表空格
比如126,+126,_ _-_ _ _ _126_ _ ,-126是有效的,输出为126,126,-126,-126;而cww126,126.45,126 ____126,cww_126,126_cww,是无效的

我要C语言的代码阿,不是C++~~
正确的话追加50分

好了,按要求做好了。
注意输入的时候可能要按两次回车。
///刚看到你给我的消息,C语言的话你把那个字符串转换到char*吧,另外注意传入数组的大小就是了。还有打印的话就是用printf了。

#include<iostream>
#include<string>
using namespace std;
bool isCharInrange(char c){ if(c>'9') return false;
else if(c<'0'){
if(c=='+'||c==' '||c=='-')
return true;
else return false;
}
else return true;

}
string trim(string s){
string result="";
for(int i=0;i<s.length();i++)
if(s.at(i)!=' ')
result+=s.at(i);
return result;
}

bool check(string s){ int i;
for(i=0;i<s.length();i++){
if(!isCharInrange(s.at(i)))
return false;
} //检查字符是否都在范围内
bool has=false;//检查是否有两个正负号
for(i=0;i<s.length();i++){
if(s.at(i)=='+'||s.at(i)=='-'){
if(!has) has=true;
else return false;
}
if(has){
s=trim(s);
for(i=0;i<s.length();i++)
if(s.at(i)=='+'||s.at(i)=='-')
if(i!=0) return false;

}
}//检查正负号的问题
int lastSpace=-1;//上一个空格的位置
bool isLastCharOpe=false;//上一个字符是不是正号或者负号
for(i=0;i<s.length();i++){
if(s.at(i)=='+'||s.at(i)=='-') isLastCharOpe=true;
else isLastCharOpe=false;

if(s.at(i)==' ') {
lastSpace=i; //空格是连续的,或者从某一个空格开始后面全是空格了。
if(!isLastCharOpe&&trim(s.substr(i,s.length())).length()==0) return true;//或者空格前一个字符不是正负号,空格后面没有数字了。
if(isLastCharOpe) continue;
if(!has) continue;
else return false;
}
}
return true;
}
void main(){
string input;
cout<<"input a string"<<endl;
getline(cin,input);
if(check(input))
cout<<"输入正确"<<trim(input)<<endl;
else cout<<"非法输入"<<endl;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2007-12-14
///////////////////大概功能实现。楼主自己看着细化吧
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void main()
{
char str[50];
while (true)
{
printf("请输入字符串: ");
scanf("%s",str);
int result=atoi(str);
if (result==0&&str[1]!='\0')
printf("结果: 你输入的不是数字\n");
else
printf("结果:%d\n",result);
}
}
第2个回答  2007-12-13
#include "stdio.h"
main()
{
float c;

while((c=getchar())!=EOF)
{
if(c=='+'||c=='-'||c>='0'&&c<='9')
putchar(c);
}
}