算法:讀取多行輸入的方式(C++)

方法1:使用 scanf() != EOF 去檢測是否讀到了文件的末尾,見函數TestOne()

方法2:使用 while(cin >> str) 讀取多個string值

待續…

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;

// 方法1:使用 scanf() != EOF 去檢測是否讀到了文件的末尾,見函數TestOne()
void TestOne()
{
	int count;
	int tmp;
	set<int> output;

	while (scanf("%d", &count) != EOF)
	{
		for (int i = 0; i < count; ++i)
		{
			cin >> tmp;
			output.insert(tmp);
		}

		for (auto iter = output.begin(); iter != output.end(); ++iter)
			cout << *iter << endl;

		output.clear();
	}
}

// 方法2:使用 while(cin >> str) 讀取多個string值
void TestTwo()
{
	string str;
	char ch;
	stack<string> s;

	while (cin >> str)
		s.push(str);

	while (s.size() > 0)
	{
		cout << s.top() << " ";
		s.pop();
	}
}

int main()
{
	TestOne();
	TestTwo();
	system("pause");
	return 0;
}

感謝閱讀

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章