我如何处理非空格分离输入C ++

时间:2017-04-08 06:37:02

标签: 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;
}

1 个答案:

答案 0 :(得分: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;
}