counting spaces

Hello. I am trying to write a code for counting number of spaces in the massive. And suddenly it doesnt work. It is always 0 in output no matter what I have wrote. Help me please! Why this doesnt work?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include<iostream>
#include<cstdio>
#include<cstring>
#include<stdio.h>
int main(void)
{
char stroka[80];
std::cin>>stroka;
int k=0;
for(int i=0; i < strlen(stroka); i++)
{if (stroka[i] == ' ')
k++;
}
std::cout<<k;
return 0;
}
I would recommend using strings. However, if you must use the C-string then to get a line of input (including whitespace characters) and store it in the line array, you would use the cin.getline(variable, size of the array)

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<cstdio> 
#include<cstring>
#include<stdio.h> // You shouldn't need this because you are calling the cstdio.
int main()
{
    char stroka[80];
    //std::cin >> stroka; The cin will stop at the first whitespace.
    std::cin.getline(stroka, 80);
    int k = 0;
    for (unsigned int i = 0; i < strlen(stroka); i++)
    {
	   if (stroka[i] == ' ')
		  k++;
    }
    std::cout << k;
return 0;
}


The following example is by using the strings library from C++:

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

int main()
{
    std::string stroka{ " " }; // Declare and initialize the variable.
    int k{ 0 }; // Initialize the counter.
    std::getline(std::cin, stroka); // getline function is used to include the whitespace.

    for (unsigned int i = 0; i < stroka.length(); i++) //length() function is to obtain the length of stroka.
    {
	   if (stroka[i] == ' ')
		  k++;
    }
    std::cout << k;

return 0;
}


I hope it helps.
Last edited on
Topic archived. No new replies allowed.