1.一行输入多个(已知个数)数据:
(1)cin >> 变量1 >>变量2 >>变量3 ...;
#include<iostream>
using namespace std;
int main() {
string s,c;
cin >> s >> c;
cout << "s = " << s << " " << "c = " << c;
return 0;
}
结果:用空格或者回车分开数据
2.一行输入多个(未知个数)数据:
(1)利用while和cin
#include<iostream>
using namespace std;
int main() {
int a[50];
int i = 0;
while (cin >> a[i]) {
cout << a[i] << " ";
i++;
}
return 0;
}
结果:
(2)利用EOF:while(scanf("%d",&n)!=EOF)
例:输入多个整数(一行),输出其中最大的整数。
#include<stdio.h>
int main(){
int n,max;
max=-1;
while(scanf("%d",&n)!=EOF) {
max=max>n?max:n;
}
printf("%d",max);
}