天天看點

面向對象程式設計第三次作業

Github位址點這裡

題目:

面向對象程式設計第三次作業
面向對象程式設計第三次作業

代碼:

main.cpp

1 #include<iostream> 
2 #include<string> 
3 #include<queue> 
4 #include<stdlib.h> 
5 #include"Calculator.h" 
6 

7 

8 using namespace std; 
9 

10 int main(void) 
11 { 
12 	Scan scan; 
13 	Print print; 
14 

15 	cout << "請輸入表達式" << endl; 
16 	string input; 
17 	cin >> input; 
18 

19 	queue<string>queue = scan.ToStringQueue(input); 
20 

21 	print.ToOutput(queue); 
22 	system("pause"); 
23 	return 0; 
24 } 
           

Calculator.h

1 #include<string> 
2 #include<queue> 
3 using namespace std; 
4 

5 class Scan 
6 { 
7 public: 
8 	queue<string>ToStringQueue(string input); 
9 private: 
 	queue<string>m_quQueue; 
11 	int    length = 0;//lengh計算數字的長度是否超标. 
12 	string trans = "";//trans将char型轉換為string型. 
13 }; 
14 

15 class Print 
16 { 
17 public: 
18 	void ToOutput(queue<string>queue); 
19 };    	
           

ScanPrint.cpp

1 #include<iostream> 
2 #include<string> 
3 #include<queue> 
4 #include<cctype> 
5 #include"Calculator.h" 
6 using namespace std; 
7 

8 queue<string>Scan::ToStringQueue(string input) 
9 { 
10 

11 	for(int i = 0; i < input.length(); i++)//掃描整個string. 
12 	{ 
13 

14 

15 		if (isdigit(input[i]) || input[i] == '.')//如果掃描到數字,對整個數字進行處理. 
16 		{ 
17 			if (input[i] == '.') 
18 			{ 
19 				i++;//如果接收到小數點,不計數,直接接收下一個數字. 
20 			} 
21 

22 			length += 1; 
23 

24 			if (length >= 10) 
25 			{ 
26 				if(!m_quQueue.empty()) 
27 				m_quQueue.pop();//當數字長度超标,清除資料 
28 

29 				cout << "數字長度超标!" << endl; 
30 
 
31 				return m_quQueue; 
32 				break; 
33 			} 
34 			 
35 			trans += input[i]; 
36 			if (!isdigit(input[i + 1])) 
37 			{ 
38 				m_quQueue.push(trans); 
39 				continue; 
40 			} 
41 		} 
42 		else//接收到的是符号 
43 		{ 
44 			trans = input[i]; 
45 			m_quQueue.push(trans);//直接進隊 
46 			trans = ""; 
47 		} 
48 	} 
49 	return m_quQueue; 
50 } 
51 

52 void Print::ToOutput(queue<string>queue) 
53 { 
54 	string Output; 
55 	while (!queue.empty()) 
56 	{ 
57 		Output = queue.front(); 
58 		cout << Output << endl; 
59 		queue.pop(); 
60 	} 
61 } 
           

運作結果

面向對象程式設計第三次作業
面向對象程式設計第三次作業

解題過程

  • 在之前的自學中,有學習到了題目中要求的string與類,但是對于queue還沒有了解。在經過查找研究之後略微知道了queue的用法。
  • 了解了queue之後,我認為題目的重點是對數字的處理,要把一個數字完整的放進隊列,并且判斷數字的長度是否超标。
  • 在編寫時,沒有熟練掌握string的+=用法,給自己帶來了很多麻煩。還去考慮通過*10來對數字進行處理。
  • 經過查找後,了解了CCTYPE函數,對判斷有了很大幫助。
面向對象程式設計第三次作業
  • 經過題目的實踐之後才算真正熟悉了C++熟悉了類熟悉了string。能夠感受到C++的便捷和魅力。