题目是:编的一个程序。从键盘输入字符串到数组中,将字符串转换为整数。不能用库函数

来源:百度知道 编辑:UC知道 时间:2024/05/29 08:22:05
#include "stdio.h"

int main()
{
char tt[30];
int i=0,value=0;
printf("input a zifuchuan:\n");
scanf("%s",tt);
while(tt[i]!='\0')
{
value=value*10+tt[i]-48;
i++;
}
prin
这是我的程序.老师说我的字符不能指定长度??

你的老师意思很明显,就是你用数组存储的话,要预先估计字符串的大小,这是不大现实,要你能够满足,不管字符串有多长,你都能够完成要求的功能。
可做如下处理,假设用户输入都是规范的。
#include<stdio.h>
#include<stdlib.h>
void main(void)
{
char temp;
int i=0,
value = 0;
while((scanf("%c",&temp))!=EOF) {
value = value*10 + temp-48;
i++;
}
}

你的程序是正确的,你们老师说的长度是什么意思?

int Nub(char *pch)
{
int i;
int cnt=0;

do
{
i=*pch-'0';

if(i>=0&&i<=9)
{
cnt *= 10;
cnt += i;
}

}while(*pch++);
return cnt;
}

main( )
{
char *ch="-153";
int nub;

if(*ch == '-')
nub = -Nub(ch);
else
nub = Nub(ch);

printf("%d",nub);
getch();
}