要求:
在屏幕中,输入一行数字,以空格分隔,其中每个数字的长度不一定一样,要求将这些数字分别存放到数组中。
例如:
输入: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型数组。
程序代码:
#includeusing 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 运行结果:
方法二:< http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+yrnTw9fWt/u0rrGjtObBrND4tcTK/dfWo6zS1LvxtcPN6tX7tcTV+8r9o6zDv7Wx0/a1vb/VJiMyNjY4NDu1xMqxuvKjrHN0cmluZ7Hkwb++zcflv9WjrMi7uvO009DCu/HIodK7uPbBrND4tcTK/dfWoaO/ydLUzai5/XN0cmluZ7XEY19zdHK6r8r9vatzdHJpbmex5MG/16q7r86qY2hhctDNtcSjrMi7uvPNqLn9YXRvabqvyv3U2dequ6/Oqsr919ahozwvcD4KPHA+PHByZSBjbGFzcz0="brush:java;">#include
#include 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
