searching space in a char

i need a function where i can find the space. this is what i have. but when i compile it it shows no errors but when i enter something it shows nothing can someone tell me why
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
	char inj[15];
	int p;
        cin >> inj;
	for (p=0;p<15;p++)
	{
		if(inj[p]==' ')
		{
		   cout << p << endl;
		}
	}
	system("pause");
        return 0;
}

output:
fail thing
press any key to continue...
You're making it print only if it's a space. It wouldn't show anything in any case.
This is because the cin>> operator only gives you everything in that stream up to the first whitespace. This lets you do things like:
1
2
3
4
5
6
7
8
int main()
{
  int a, b, c;
  cout << "Enter 3 numbers: ";
  cin >> a >> b >> c;
  cout << "The 3 numbers are: " << a << ", " << b << ", " << c << endl;
  return 0;
}
Enter 3 numbers: 2 45 76
The three numbers are: 2, 45, 76
press any key to continue...


Instead of the cin>> operator, use the getline() function from istream like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
	char inj[15];
	int p;
        cin.getline(inj,15);
	for (p=0;p<15;p++)
	{
		if(inj[p]==' ')
		{
		   cout << p << endl;
		}
	}
	system("pause");
        return 0;
}


This will insert everything into inj.

Reference:
http://cplusplus.com/reference/iostream/istream/getline/
Last edited on
@ciphermagi: He's outputting the index, not the value of inj[p]. That was my original thought too until I took a second look.
thanks
Last edited on
I see it now. Yes, cin >> will only read up to (and not including) the first white space character.
#include <iostream>
using namespace std;

int main()
{
char inj[15];
int p;
int how_many = 0;
cin.getline(inj, 15);
for (p = 0; p < 15; p++)
{
if(inj[p]==' ')
{
++ how_many;
cout << "space encountered on line # " << p + 1 << endl;
}
}
if (how_many == 0)
cout << "\nno spaces encountered.\n";
else if (how_many > 0)
cout << endl << how_many << " total spaces encountered.\n";
cout << "\npress enter to exit.";
cin.get();

return 0;
}

//will count and report how many total spaces and their locations on the screen.
Topic archived. No new replies allowed.