[英]whitespace identification in c++
我的代碼必須使用cin識別空格字符,因此當我使用空格作為輸入時,它應該識別空格。 我該怎么做呢?
您可以使用std::noskipws
禁用默認情況下跳過std::cin
的空格:
#include <iostream>
#include <iomanip>
int main() {
char c;
std::cin >> std::noskipws;
while (std::cin >> c) {
if (c == ' ')
std::cout << "A space!" << std::endl;
}
return 0;
}
string str;
getline(cin, str); // get the whole line
如果要處理c字符串,可以使用上述cin.getline(....)
,它與字符串getline
不同。
Cin打破了任何空白。 如果需要讀取整行,則需要使用get line函數:
getline(cin, line);
其中line是std :: string。 這仍然會切斷所有新行或回車符。
要測試字符串中的空格,請檢查字符串中的每個字符,並將其與空格字符“”進行比較。 那留給讀者練習;)
使用cin.getline讀取帶有空格的行。
http://www.cplusplus.com/reference/iostream/istream/getline/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.