包含头文件的问题之1.7编程基础之字符串 24:单词的长度

1.7编程基础之字符串 24:单词的长度
注意头文件 #include<string>和#include<cstring>不通用

 1 #include<iostream>
 2 #include<string>
 3 #include<cstring>
 4 #include<cstdio> 
 5 using namespace std;
 6 char a[1001];
 7 int main()
 8 {    
 9 //    cin>>a;cout<<strlen(a);
10 //    while(cin>>a){cout<<','<<strlen(a);    }//最简方法 ,cin和scanf("%s",s)类似,遇到空格结束。
11     int len,s=0,word=0;
12     gets(a);                            //使用cstdio头文件
13     len=strlen(a);                        //在niop题库中需使用cstring头文件 ,虽然可能在windows下不用 
14     for(int i=0;i<len;i++)
15     {
16         
17         if(a[i]==' '&&word==0)
18         {
19             cout<<s<<',';word=1;s=0;
20         }
21         else if(a[i]!=' ')
22         {
23             s++;word=0;
24         }
25         
26     }
27     cout<<s<<endl;
28     return 0;
29 }

上面程序只适用于输入数据只有一行的情况,下面使用geline,stringstream解决多行输入问题
stringstream字符串流可以实现类似sscanf和sprintf的功能:

#include<iostream>
#include<string>
#include<cstring>
#include<sstream> 
using namespace std;

int main()
{	
	string s;char a[1001];
	while(getline(cin,s))
	{   
		int t=1;
		stringstream ss(s);
		for(int i=0;ss>>a;i++)
		{
			if(t){	t=0;cout<<strlen(a);	}
		    else cout<<','<<strlen(a);
		}
	
	}

	return 0;
}

  

下面是一个 stringstream字符串流的例子
/*读入两个整数,中间用空格隔开,输出他们的和*/

#include <cstdio>
#include <sstream>
#include <iostream>
#include<string>
using namespace std;
#define MAXN 100010
int main()
{
    char s[1000];
    cin.getline(s,1000,'\n');
	//string s;getline(cin,s); //用这句功能类似 
    stringstream  ss(s);
    int a,b;
    ss>>a>>b;  //类似sscanf(s,"%d%d",&a,&b);
    cout << a+b << "\n";
    return 0;
}

  

转载于:https://www.cnblogs.com/jchm/p/5458666.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值