摘要
本文首先 在实现中 字符串 格式化输入函数上 遇到的一个问题。其次 ,讲解 如何 处理 字符串转换为 整型常量的 实现。最终, 文章将给出 整型常量 变为 字符串的实现 源代码。
1. 编程中 格式化输入函数 遇到的一个小问题
下面这段代码 字符串输入 在句法上是没有问题的(编译、连接不会报错),但是显然会在程序运行时出错:
[cpp] view plain copy int main() { char * teststr; scanf("%s",teststr); int myint = 0; for(int i = 0; teststr[i] ; i++) { PRintf("%c/n",teststr[i]); } return 0; }原因在于 teststr 是一个指针,指针指向的是未知的一段内存单元。因为,位置未知,所以,有可能指向的内存或许存储着代码、数据,且它们是对程序有关键作用的内存段,这就会破坏程序!!!所以,指针应该指向一个 规范好的内存单元,由此,程序作如下修改:
将char * teststr;修改为 :
[cpp] view plain copy char * teststr; char getstr[100]; teststr = getstr;即,将指针有一个确定的地址,将 teststr 指向一个数组元素的首元素,然后输入一个字符串,把它存放在该地址的若干单元中,全部字符串输入代码如下:
[cpp] view plain copy int main() { char * teststr; char getstr[100]; teststr = getstr; scanf("%s",teststr); int myint = 0; for(int i = 0; teststr[i] ; i++) { printf("%c/n",teststr[i]); } return 0; }2. 不使用库函数,字符串转换为整数
得到字符串之后,将字符串逐个与 ‘0’ 作差,再与10倍乘,作和,直到字符串为空,得到 所求整数。
[cpp] view plain copy int main() { char * teststr; char getstr[100]; teststr = getstr; scanf("%s",teststr); int myint = 0; for(int i = 0; teststr[i] ; i++) { myint = myint*10+teststr[i]-'0'; printf("%c/n",teststr[i]); } printf("%d/n",myint); getchar(); return 0; }3. 不使用库函数,变整数为字符串
将数字逐个读入,取整取余实现数字摘取,与 ‘0’作和 ,实现整数与字符转换,下面给出 输入数字 输出 字符串 实现源码
[cpp] view plain copy #include <iostream> #include <stdio.h> int main() { int myint; std::cout<<"*********************************"<<std::endl; std::cout<<"请输入 您需要转换的整数 :"; scanf("%d",&myint); std::cout<<"*********************************"<<std::endl; char inistr[100]; char mystr[100]; int mynow; int mynext = myint; int testint = myint; for(int i = 0; mynext>0 ; i++) { mynow = testint%10; mynext = testint/10; testint = mynext; inistr[i] = '0'+mynow; } std::cout<<"您 输入的 数字 转换为 字符 之后 输出如下:"<<std::endl; int j = 0; i = i-1; for( ; i>=0 ; i--) { mystr[j] = inistr[i]; std::cout<<mystr[j]<<' '; j++; } std::cout<<std::endl; std::cout<<"*********************************"<<std::endl; getchar(); return 0; }转载地址:http://blog.csdn.net/u013630349/article/details/44044211
新闻热点
疑难解答