要求:
在屏幕中,输入一行数字,以空格分隔,其中每个数字的长度不一定一样,要求将这些数字分别存放到数组中。
例如:
输入:1 123 1234 22 345 25 5
对应的数组的值应该为a[0]=1,a[1]=123,a[2]=1234,a[3]=22,a[4]=345,a[5]=25,a[6]=5;
输入:2345 23 124 2
对应的数组的值应该为a[0]=2345,a[1]=23,a[2]=124,a[3]=2;
这个问题的难点是如何在输入的一串字符中找到连续的数字作为一个数值,然后保存到数组中。
方法一:
利用getchar函数和ungetc函数,通过getchar函数判断回车,以及判断时候为数字,然后通过ungetc函数,将通过getchar函数获得的字符送回缓冲区,再通过cin函数取出作为int型数组。
程序代码:
#include<iostream> using namespace std; int main() { int a[50]; int i = 0; char c; while((c=getchar())!='\n') { if(c>='0'&&c<='9') { ungetc(c,stdin); cin>>a[i++]; } } for(int j=0;j<i;j++) { cout<<"a["<<j<<"]:"<<a[j]<<endl; } }运行结果:
方法二:
使用字符串保存连续的数字,以获得完整的整数,每当遇到空格的时候,string变量就清空,然后从新获取一个连续的数字。可以通过string的c_str函数将string变量转化为char型的,然后通过atoi函数再转化为数字。
#include<iostream> #include<cstdlib> using namespace std; int main() { int a[50]; int i = 0; char c; string str = ""; while((c=getchar())!='\n') { if(c>='0'&&c<='9') { str += c; } else if(c ==' ') { a[i++] = atoi(str.c_str()); str = ""; } } for(int j=0;j<i;j++) { cout<<"a["<<j<<"]:"<<a[j]<<endl; } }