program_g21 program_g21 - 21 days ago 5
C++ Question

Find length of the string(excluding spaces)?

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char name[10];
char op;
int w, len;
cout<<"Menu\n1.Length of the string(with & without spaces)\n" \\I have edited out the rest as it was irrelevant to my question
cin>>op;
switch(op)
{
case '1': cout<<"Enter a word";
gets(name);
w=strlen(name);
cout<<"The length of the string including spaces is"<<w;
for(int i=0;i!=w;++i)
{
if (name[i]!=' ')
{
len++;
}
}
cout<<"Excluding spaces is\n"<<len;
}
getch();
}


I'm using Turbo C7 compiler for this program.
It displays including spaces value, but not excluding spaces.
Please correct the code if it's wrong.

Answer

Use String.length() and change your input to String type. Don't forget to #include <string>.

int len = 0;

string Input;
getline(cin, Input);

for (int x = 0; x < Input.length(); x++) {
    if (Input[x] != ' ') {
        len++;
    }
}

cout << len;

This will work without any problems.