2017-04-08 36 views
-2

我想計算網格中'#'的數量。如果輸入是空格分隔的,則不起作用,但如果不是,則不起作用。我如何使第一個工作?我如何接受非空間分離的輸入C++

3 3 3 3 
.## . # # 
#.# # . # 
### # # # 
Fails Works 
using namespace std; 
int main() { 
    int h, w, i, o, total = 0; 
    string current; 
    cin >> h >> w; 
    for (i = 0; i < h; i++) { 
     for (o = 0; o < w; o++) { 
      cin >> current; 
      if (current == "#") { 
       total += 1; 
      } 
     } 
    } 
    cout << total; 
} 
+2

定義爲char電流 –

回答

2

這是因爲當你給不空格分隔的輸入,那麼它需要整個行作爲一個字符串,因爲當你輸入一個空格或返回字符串僅終止。
因此,在您的情況下,您將字符串作爲「。##」,那麼您將其與「#」進行比較,即返回false。這是它失敗的原因。

如果你想使它空格隔開,那麼你可以使用此代碼

#include <iostream> 
#include <conio.h> 

using namespace std; 

int main() { 
    int h, w, i, o, total = 0; 
    char current; 
    cin >> h >> w; 
    for (i = 0; i < h; i++) { 
     for (o = 0; o < w; o++) { 
      current = getch(); 
      cout << current; 
      if (current == '#') 
       total += 1; 
     } 
     cout << endl; 
    } 

    cout << total; 
} 
相關問題