program to read a string and prints its length excluding spaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<stdio.h>
#include<string.h>
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
char astr[51];
int length,len=0;
cout<<"\n Enter a string\n";
gets(astr);
length=strlen(astr);
puts(astr);
cout<<length;
for(int i=0;i<=length-3;i++);
{if(astr[i]==' ')
 { len--;
 }
 else{
 len++;
 }
}
cout<<"actual lenth without spaces"<<len;
getch();
return 0;
}


desired result is not achieved
please tell me where i am doing wrong
That would be a bit hard, because there's an error in almost every line.
To sum it up: use the correct names of the headers (cstdio, iostream, etc.), do not use C strings, do not use gets, do not use non-standard functions, use proper indentation.
After you've fixed that, we can get to the actual logic problem (if it still exists after the fixes).
There are a lot of errors in your code and most of the code is not needed. You can minimalize your code in the following way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;

int main()
{    
    int stringLength = 51;
    char astr[stringLength];
    int noSpaceLength = 0;
    
    cout << "Enter a string: ";
    cin.getline(astr, 51);
    
    cout << "Total string length: " << strlen(astr) << endl;
    
    for(int i = 0; i < strlen(astr); i++)
    {
        if(astr[i] != ' ')
        { 
            noSpaceLength++;
        }   // end if
    }   // end for

    cout << "Actual length without whitespace: " << noSpaceLength << endl;
    
    return 0;
}   // end main 


Athar >> Don't be hatin' on the C-Strings!!! They can be fun to play with!
Last edited on
Topic archived. No new replies allowed.