# 【1-4】輸入 大家應該對 Scratch 不陌生吧? 我們在 Scratch 中會使用「詢問...並等待」這個積木,來取得使用者輸入的資訊。 ![image](https://hackmd.io/_uploads/SJBMqwB4ee.png) ![image](https://hackmd.io/_uploads/SyuX5PSExe.png) 在 Python 中,我們使用 `input()` 來取得輸入內容。 ## 輸入指令-cin C++ 的輸入指令是 `cin`,透過 `>>` 來連接想要輸入的內容。 值得一提的是,在輸入前,要先替即將輸入的內容宣告一個合適型別的變數,接著才使用 `cin` 來把內容存入變數中。 ```cpp int a; cin >> a; ``` ### Python對照 ```python a = int(input()) ``` --- 如同 `cout`,`cin` 也可以做連續輸入。 ```cpp int a, b, c; cin >> 變數a >> 變數b >> 變數c; ``` ### Python對照 ```python a, b, c = map(int, input().split()) ``` ## getline `cin` 在遇到空格的時候就會停止讀入,但有時候是一段話要輸入,這時候我們就可以用 `getline()` 來讀取整行: ```cpp string 變數; getline(cin, 變數); ``` ### Python對照 ```python line = input() ``` 常搭配 `cin.ignore()` 使用,將殘留在緩衝區的換行符號清除掉。(看不懂可以等[【4-0】進階架構](https://hackmd.io/@LAfWxjSxRASps-4O_bppsA/B1mq3Pmrxx) 後再回來學) ```cpp= int a; cin >> a; cin.ignore(); // 清除換行符號 string line; getline(cin, line); // 讀取整行,儲存到 line 中 ``` ### Python對照 ```python= a = int(input()) line = input() ``` Python 中,`input()` 每次都會讀掉整行(包含換行符號,並自動去掉),所以不會殘留在緩衝區,也不會影響下一次的輸入。 --- ## 練習題 [U0003-這是一個XXX](https://code.dali.tc.edu.tw/problem/U0003) [U0004-菜菜撈撈](https://code.dali.tc.edu.tw/problem/U0004) --- 聯絡方式:codecodefunny@gmail.com 最後編修時間:2025/07/15 子柚筆