C/C++关于处理输入格式问题

一、输入未知长度字符数组,以空格分开,例如1 2 3 4,以“换行”表示结束

注:getchar()会吸收字符,所以一定要放在scanf或cin后使用;scanf/cin默认以空格分开为下一个字符,如果不输入空格,scanf会默认是一个字符。

1.while(1){      }

#include<bits/stdc++.h>
using namespace std;

int main(){
	char a[100];
	int i=0;
	while(1){
		cin>>a[i++];
		if(getchar()=='\n')
			break;	
	}
	for(int j=0;j<i;j++){
		cout<<a[j];
	}
	return 0;
}

2.do...while

#include<bits/stdc++.h>
using namespace std;

int main(){
	char a[100];
	int i=0;
	do{
		cin>>a[i++];
	}while(getchar()!='\n');
	for(int j=0;j<i;j++){
		cout<<a[j];
	}
	return 0;
}

二、输入未知长度字符串,字符串之间以空格分开,例如ab cd es,以“换行”表示结束

#include<bits/stdc++.h>
using namespace std;

int main(){
	string s[100];//string
	int i=0;
	while(1){
		cin>>s[i++];
		if(getchar()=='\n')
			break;	
	}
	for(int j=0;j<i;j++){
		cout<<s[j]<<" ";
	}
	return 0;
}

 

三、多组样例输出,以“0”结束

样例输入:15 Aab3 7

int a,b;
char str[100];
while(scanf("%d%s%d",&a,str,&b)!=EOF){
        if(a==0)
            break;
}
int a,b;
while(cin>>a>>b){

}

四、样例输入:asde 3

以“空格或换行”分开

        int n,i,j;
	char a[100];
	scanf("%s",a);
	scanf("%d",&n);
	int len=strlen(a);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值