作者macodolau (macodolau)
看板NTUBIME-99
標題[學業]關於 getline(cin,xxx) 問題討論 ~
時間Tue Oct 17 13:40:59 2006
有同學問到 getline 的用法,在這裡做個小小的範例說明~
這是屬於"字元字串處理函式",就要講到字元及字串的觀念!
這相當有得討論,應該會在未來課程裡介紹,我只做幾個小範例討論~
< 小觀念補給 >
cin 以空白做分隔,當你輸入Enter後,做會儲存到空白字元~
如:
string test;
cin >> test;
cout << test ;
--程式執行時-------------------------
aaaaa bbbb cccc <-Enter ~ 使用者輸入
aaaaa ~ 螢幕顯示
-------------------------------------
<範例 1>
#include "stdafx.h"
#include <iostream>
#include <string> // string.h為舊式的c++ compilier; string為新的c++ compilier
using namespace std ;
void read_CharStri(); // 由鍵盤讀取存到字元陣列
void read_Stri(); // 由鍵盤讀取存到字串
int _tmain(int argc, _TCHAR* argv[])
{
read_CharStri();
read_Stri();
return 0;
}
void read_CharStri()
{
char charstri[80]; // 宣告一個字元陣列(大小為80)
cout << "--使用字元陣列當字串-------------------------" << endl << endl;
cout << "輸入字串(可按 Space 試試看),按 Enter 顯示 :" << endl;
cin >> charstri ;
cout << charstri << endl << endl;
cout << "---------------------------------------------" << endl ;
system("PAUSE");
system("cls"); // 清除螢幕
}
void read_Stri()
{
string str;
cout << "--使用字串變數-------------------------------" << endl << endl ;
cout << "輸入字串(可按 Space 試試看),按 Enter 顯示 :" << endl;
cin >> str ; // 必include <string>,讀取到空白字元為止
cout << str << endl << endl;
cout << "---------------------------------------------" << endl ;
system("PAUSE");
system("cls");
}
<範例 2> 關於 "getline"
#include "stdafx.h"
#include <iostream>
#include <string> // string.h為舊式的c++ compilier; string為新的c++ compilier
using namespace std ;
void read_Space_Stri(); // 由鍵盤讀取到字串(讀取一整行,包含空白字元)
int _tmain(int argc, _TCHAR* argv[])
{
read_Space_Stri();
return 0;
}
void read_Space_Stri()
{
string str;
cout << "--可在字串中加入Space------------------------" << endl << endl;
cout << "輸入字串(可按 Space 試試看),按 Enter 顯示 :" << endl;
getline(cin,str) ; // 讀取一整行(包含空白字元)
cout << str << endl << endl;
cout << "----------------------------------------------" << endl ;
system("PAUSE");
}
有興趣的同學,Try Try See 吧 ~ !!
計程子爺助教
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.94.126