编程计算一句英文里有多少个单词,输出单词个数和每一个单词,名外再将一个数值型字符串转换成整数输出。

编程计算一句英文里有多少个单词,输出单词个数和每一个单词,名外再将一个数值型字符串转换成整数输出。

代码如下:

#include <stdio.h>
#include <map>
#include <vector>
#include <string>
using namespace std;

//字符串分割成小字符串
void SplitStr(std::string pStr, char ch,std::vector<std::string>& vReturn)
{
	int nStartPos=0;
	int nEndPos=0;
	while((nEndPos = pStr.find(ch,nStartPos))> 0)
	{
		vReturn.push_back(pStr.substr(nStartPos,nEndPos - nStartPos));
		nStartPos = nEndPos+1;
	}
	nEndPos=pStr.find('\0',0);
	vReturn.push_back(pStr.substr(nStartPos,nEndPos-nStartPos));
}


int main()
{
	char buf[1024] = {0};
	printf("请输入一句英文:");
	gets(buf);
	//
	vector<string> vout;
	SplitStr(buf,' ',vout);
	map<string,int> mapcnt;
	map<string,int>::iterator it = mapcnt.begin();
	for (int i = 0; i<vout.size(); i++)
	{
		if (vout.at(i).empty())
			continue;
		else
		{
			it = mapcnt.find(vout.at(i));
			if (it == mapcnt.end())
			{
				mapcnt.insert(pair<string,int>(vout.at(i),1));
			}else
			{
				int cnt = it->second;
				cnt+=1;
				mapcnt.erase(it);
				mapcnt.insert(pair<string,int>(vout.at(i),cnt));
			}
		}
	}
	//打印输出
	for ( it = mapcnt.begin(); it != mapcnt.end(); it++)
	{
		printf("%s:%d\n",it->first.c_str(),it->second);
	}


	//数值型字符串转数值
	char tmp[8] = {0};
	printf("请输入数值型字符串:");
	scanf("%s",tmp);

	int vv = 0;
	string ss = tmp;
	int index = ss.find('.');
	if (index == -1)
	{
		vv = atoi(tmp);
	}else
	{
		ss = ss.substr(0,index);
		vv = atoi(ss.c_str());
	}

	printf("%d",vv);
	getchar();
	getchar();
	return 0;
}