2013-03-28 29 views
0

輸入小數點後是否有任何方法去除尾部空白? 例如:僅通過istream函數從輸入流中刪除空格

10  A 

我想捕捉空白結束後的第一個字符。 (這得是的\ n是真的如果不是,那麼假

我試圖至今:?

cout << "Please enter a number: "; 
cin >> n; 

if (cin.peek() == ' ') 
    //Something to catch the whitespaces 

if(cin.fail() || cin.peek() != '\n') 
    cout << "Not a number." << endl; 

else 
    cout << "A number." << endl; 

能夠做到這一點功能的IStream

(我知道cin.fail可以做好事,但它仍然不會考慮輸入10A作爲失敗)

+0

只是讓整條生產線,你應該找到生成的字符串要好得多檢索信息。 – chris 2013-03-28 04:17:29

+0

http://stackoverflow.com/questions/710604/how-do-i-set-eof-on-an-istream-without-reading-formatted-input – 2016-04-12 06:05:40

回答

0

感謝您的幫助。 使用字符串它確實很容易。雖然不允許使用它。

可以通過這種簡單的方法來完成:

cout << "Please enter a number: "; 
cin >> n; 

while (cin.peek() == ' ') 
    cin.ignore(1,' '); 

if(cin.fail() || cin.peek() != '\n') 
    cout << "Not a number." << endl; 

else 
    cout << "A number." << endl; 
+3

'while'循環可以被一個調用替換到[**'std :: cin >> std :: ws;'**](http://en.cppreference.com/w/cpp/io/manip/ws)。 – 0x499602D2 2014-01-19 16:52:43

+1

@ 0x499602D2你在某個地方回答了這個問題嗎?這就是我來這裏尋找的答案,我想加入它。 – 2015-02-11 13:36:03

1

正如@chris所說,你真的想從閱讀一整行開始,然後從那裏閱讀其餘的內容。

std::string line; 
std::getline(cin, line); 

std::stringstream buffer(line); 

buffer >> n; 

char ch; 
if (buffer >> ch) 
    cout << "Not a number"; 
1

我對你試圖做的事有點困惑。你是說你想避免空白嗎?

cin跳過那些...它是一個有效的空白分隔符,如選項卡或換行符。如果你這樣做:

int A(0), B(0); 

std::cin >> A >> B; 

進入將在走,直到你鍵入一個空格的數字,那麼他們將在B.去

如果您正在使用的字符串,並希望它們連接成一個不帶空格;

std::string A, B, C; 
std::string final; 

std::cin >> A >> B >> C; 

std::stringstream ss; 
ss << A << B << C; 
final = ss.str(); 

然而,像傑裏提到的,如果你處理字符串,你可以做的std ::函數getline(),它會給你可能較麻煩。