如图,我现在需要这样的一个数组,假如我输入n = 4, 然后我依次输入
1 2
这里的1和2之间有个空格,2后面有个回车
最后得到的结果就是arr[0] = 1, arr[1] = 2,后面的为空
谢谢大家了
因为你的要求是int,所以后面没有赋值的一般是初始为0
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int n;
cout << "Pls enter arr count: \n";
cin >> n;
int *a = new int[n];
memset(a,0x0,n*sizeof(int));//将数组全部元素赋予0
int i = 0;
int value = 0;
cout << "Pls enter exit number: \n"; //为了在n范围内退出输入循环
int exitNub = -1;
cin >> exitNub;
cout << "Pls enter your arr e.g: 1 2 " << exitNub << "(exit input)\n";
for(;i<n && cin >> value;i++)//i<n防止数组越界
{
if(value == exitNub) //在n的范围内遇到退出数则不再输入
break;
a[i] = value;
}
cout << "\n******************Output****************** " << endl;
for(int j=0;j<n;j++)
{
cout << a[j] << " ";
}
cout << endl;
return 0;
}
就是说你不知道要输入几个数字呗,这样的话你可以
int tmp;
string s;
cin >> s;
ofstream out;
ifstream in;
out << s;
while(in >> tmp) {
a[i] = tmp;
i++;
}
int n;
int *arr;
int tmp, i=0;
cin >> n;
arr = new int[n];
while(cin >> tmp){
arr[i++] = tmp;
}
回车后输入ctrl+z结束输入。
你这个情况实际是要求回车标志cin输入流的结束(EOF),但一般不会用到这种情况,因为cin一般是需要持续输入的,不会遇到EOF。
这种情况下只能手动输入EOF(ctrl+z)。如果直接用cin输入,空格和回车都会被认为是分割输入变量的符号,不会用作其他用途,所以如果想用回车结束输入只能介入其他办法。
楼上可能想使用的方法是整行读入,然后把这行的字符串重新作为输入处理,这样这个字符串输入结束就等价于遇到回车结束了,但是不知道这哥们是真不会还是搜了搜就来凑数的,简直就是瞎写。
PS:NR指数组个数的上限。
# include <cstdio>
# include <iostream>
# include <cmath>
# include <cstring>
# include <algorithm>
using namespace std;
# define FOR(i, a, b) for(int i = a; i <= b; i++)
# define _FOR(i, a, b) for(int i = a; i >= b; i--)
const int NR = 100;
int n;
int a_len, a[NR + 10];
int main()
{
scanf("%d", &n);
char ch = ' ', ch_prev;
int now = 0;
bool ntl = true;
scanf("\n");
while(ch != '\n'){
scanf("%c", &ch);
if(a_len == n) continue;
if(ch <= '9' && ch >= '0') now = now * 10 + ch - '0';
else if(ch == '-') ntl = false;
else if(ch_prev != ' '){
if(!ntl) now = -now;
a[a_len++] = now;
now = 0;
ntl = true;
}
ch_prev = ch;
}
FOR(i, 0, a_len - 1) printf("%d ", a[i]);
puts("");
return 0;
}