2017-04-08 38 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; 
} 
相关问题