[C ++] - merge solution to a problem of cattle off the input stream

Merge input streamHere Insert Picture Description

The title is simple, but not easy to do (I may be dumb, trained, trained, trained)

Idea: Because the question, said input separated by a space, so we will enter two strings, according to the first open space division, respectively, into vector, then we must pay attention to several points:
1, string 1 has been the output end, the output end of the string 2 is not
2, the output end of the string 2, but not an output end

Here is the code:

#include  <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
using namespace std;
vector<string> Splict(string str, string s)
{
	str += s;
	vector<string> v;

	int pos = str.find(s);
	while (pos!= string::npos)
	{
		string ret = str.substr(0, pos);
		v.push_back(ret);
		str = str.substr(pos + 1);  //str为pos+1后面的字符串
		pos = str.find(s);
	}
	return v;
}
int main()
{
	string str1;
	string str2;
	getline(cin, str1);
	getline(cin, str2);
	vector<string> v1;
	v1=Splict(str1, " ");
	vector<string> v2;
	v2 = Splict(str2, " ");
	int flag = 0;
	for (int i = 0, j = 0; i < v1.size();)
	{
		for (int k = 0; k < 4; k++)
		{
			cout << v1[i++] << " ";

			if (i >= v1.size())
			{
				flag = 1;  //说明v1已经输出完了
				break;
			}
		}
		if (j >= v2.size())  //判断v2是不是比v1先输出完成,否则会发生断错误
		{
			for (; i < v1.size();)
			{
				cout << v1[i++] << " ";
			}
			break;
		}

		if (flag)  //v1已经输出完了,判断v2是否已经输出结束
		{
			for (;j < v2.size();)
			{
				cout << v2[j++] << " ";
			}
		}
		else
			cout << v2[j++] << " ";
	}
	system("pause");
	return 0;
}
Published 42 original articles · won praise 13 · views 1761

Guess you like

Origin blog.csdn.net/Vicky_Cr/article/details/105320490