Iroh4526
Iroh4526

Reputation: 103

How can I get the number of characters from an input string?

I am trying to count the number of characters in a string that is provided by the user. I know I can use string::length() and string::size() but when a space is encountered, the count is stopped. For example, say the user inputs "Bob Builder", the count should be 10 but what my code would display would be 3. Also I am trying to do this without using a character array. Any suggestions? An explanation would also greatly help.

    int main()
    {
       string Name;
       cin>>Name;
       cout << name(Name);
       return 0;
    }

    int name(string a)
    {
        int numChar;
        /*for (int i=0; a[i] != '\0';i++)
        {
             if (!isspace(a[i]))
             numChar++;
        }*/
        numChar=a.length();
        return numChar;
   }

Upvotes: 3

Views: 586

Answers (2)

You have to use getline() instead of cin to get all line up to newline. cin reads input up to whitespace.

std::getline (std::cin,Name);

If you use using namespace std;

getline (cin,Name);

If you want to count the input string excluding spaces, the code snippet helps you.

#include <algorithm>
#include <string>

int main() 
{
    std::string s = "Hello there, world!";
    std::cout << std::count( s.begin(), s.end(), ' ' ) << std::endl;
}

Upvotes: 2

marom
marom

Reputation: 5230

How yu know when input is over? If you want to read until end of line then this is a possible solution:

std::string line ;
std::cin.getline(line) ;
line.length() ;

Upvotes: 3

Related Questions