counting letters in a string, excluding spaces
Oct 16, 2014 at 3:13am UTC
I'm trying write a bit of code that will count the number of letters in a name (first, middle, last) but not count the spaces. What I have here almost work, but it seems to ignore only the first space. (Yes, it also prints the name back words - silly I know).
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 28 29 30 31
#include <iostream>
#include <string>
int x;
int char_count = 0;
using namespace std;
int main ()
{
string user_name;
cout << "To see your name spelled backwards, enter your" ;
cout<< " name here: " << endl;
getline(cin, user_name);
for (x = user_name.length()-1; x <= user_name.length(); --x)
{
cout << user_name.at(x);
char_count++;
if ( x == '\n' )
char_count--;
}
cout << "\n" << char_count << " letters\n" << endl;
return 0;
}
To see your name spelled backwards, enter your name here:
Bill W Smith
htimS W lliB
11 letters
Oct 16, 2014 at 3:23am UTC
if (name.at(x)==' ' )continue
Oct 16, 2014 at 3:34am UTC
int len = user_name.length();
for ( int i=0; i< user_name.length(); i++ )
if ( user_name[i] == ' ') len--;
Oct 17, 2014 at 9:56pm UTC
Thanks you!
Topic archived. No new replies allowed.