-1

I created a program that the user enters a string. But i need to count how many letters are in the string. The problem is im not allowed to use the strlen()function. So i found some methods but they use pointers but im not allowed to use that yet as we havent learned it. Whats the best way to do this in a simple method? I also tried chars but i dont have luck with that either.

#include <iostream>

using namespace std;

string long;
string short;


int main()
{

        cout << "Enter long string";
        cin >> long;


        cout << "Enter short string";
        cin >> short;



    return 0;
}

I need to get the length of long and short and print it.

I am trying to use it without doing strlen as asked in some previous questions.

soniccool
  • 5,790
  • 22
  • 60
  • 98

3 Answers3

3

Do you mean something like this?

//random string given

int length = 1;
while(some_string[length - 1] != '\0')
  length++;

Or if you don't want to count the \0 character:

int length = 0;
while(some_string[length] != '\0')
  length++;
codingEnthusiast
  • 3,800
  • 2
  • 25
  • 37
1

You can count from the beginning and see until you reach the end character \0.

std::string foo = "hello";

int length = 0;
while (foo[++length] != '\0');

std::cout << length;
allejo
  • 2,076
  • 4
  • 25
  • 40
1

If you use standard cpp string object I think the best way to get length of your string is to use method:

long.size();

It gives you number of characters in string without end string character '\0'. To use it you must include string library :

#include <string>

If you decide to use char table you can try method from cin:

char long_[20];
cout << "Enter long string\n";
int l = cin.getline(long_,20).gcount(); 
cout << l << endl;

gcount()

ElConrado
  • 1,477
  • 4
  • 20
  • 46