[英]how to use cin.ignore to ignore specified character in C++
我想使用cin.ignore()從鍵盤獲取數據。 示例:我輸入了一個字符串“ 12/12/2015”。 我如何忽略“ /”以獲取諸如“ 12122015”這樣的字符串。由於我在書中讀過(如何編程c ++,deitel),他們使用cin.ignore來做到這一點,但現在我找不到了在哪兒? 感謝您的幫助!!!
您必須手動處理
cin.ignore以另一種方式工作。 見cplusplus
istream&忽略(streamsize n = 1,int delim = EOF);
從輸入序列中提取字符並丟棄它們,直到提取出n個字符或一個等於delim的比較字符為止。
可能是簡單的解決方案: 替換\\刪除字符串中的字符
您可以讀取固定數量的字符,然后使用cin.ignore(1)
跳過以下字符,但這不是很優雅。 如果我是你,我將使用getline
,並將行尾定界符設置為'/'
:
string day, month, year;
getline(cin, day, '/');
getline(cin, month, '/');
// and the rest is assumed to be the year
cin >> year;
string date = day + month + year;
cout << date << '\n';
但是,如果您真的想使用cin.ignore
,這是這樣的(我認為,一段時間以來沒有使用C字符串,似乎給出了正確的結果):
char day[3], month[3], year[5];
cin.get(day, 3);
cin.ignore(1);
cin.get(month, 3);
cin.ignore(1);
cin.get(year, 5);
string date = string(day) + string(month) + string(year);
cout << date << '\n';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.