获取全部不定长数据
C++
#include <iostream>
using namespace std;
int main()
{
int n;
while (cin >> n){ //输入没有结束,cin 就返回 true,条件就为真
cout << n;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n;
while (cin.get() != EOF){//get不会从缓冲区中删除字符
cin >> n
cout << n;
}
return 0;
}
C
#include <stdio.h>
int main() {
char ch;
int num;
while (
ch = getchar()
&& ch != EOF
&& ungetc(ch, stdin)
) {
scanf("%d", &num);
printf("%d ", num);
}
}
获取一行不定长数据
C++
#include <iostream>
using namespace std;
int main()
{
int n;
while (cin.get() != "\n"){ //输入没有结束,cin 就返回 true,条件就为真
cin >> n
cout << n;
}
return 0;
}
#include<sstream>
#include<string>
int main(){
string s;
getline(cin, s)
istringstream iss(s);
while(iss >> num){
//do sth
}
}
C
#include <stdio.h>
int main() {
char ch;
int num;
do {//getchar会从缓冲区中删除字符
do {
scanf("%d", &num);
printf("%d ", num);
} while ((ch = getchar()) && ch != '\n' && ch != EOF && (ungetc(ch, stdin)));
printf("\nanother line\n");
} while (((ch = getchar()) && ch != EOF) && (ungetc(ch, stdin)));
}
版权声明:本文为lgfx21原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。