Spaces in Char array

Sep 29, 2011 at 8:41pm
im making a program that requires the ability to destinguish between spaces in an array, but for some reason, c++ isnt really acting the way i would expect it to. For example, here is the code that i wrote to try to identify the problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main()
{
    char array[100];

    cin >> array;

    for (int i = 0; i < 100; i++){
        if (array[i] == ' '){
        cout << "space" << endl;
        }

        if (array[i] != ' '){
        cout << "no space" << endl;
        }
    }

    return 0;
}


if you compile it, it will never output "space", even if you enter spaces in your imput. Why is this happening? is there any way to make this work?
Sep 29, 2011 at 9:00pm
The >> operator skips spaces. Try using:
1
2
3
4
5
std::string line;

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

///  etc... 

Sep 30, 2011 at 5:04am
try if(array[i]==char(32))cout<<"space";//in your for loop
Sep 30, 2011 at 10:27am
thanks. its working great now
Sep 30, 2011 at 10:31am
what is char (32)?
Sep 30, 2011 at 10:38am
char(32) is exactly the same as ' '.

32 is the raw number that the computer uses to represent a space character.
Last edited on Sep 30, 2011 at 10:38am
Topic archived. No new replies allowed.