Click to See Complete Forum and Search --> : calculating length of string
kirtipriyanka
November 3rd, 2007, 05:29 PM
#include<iostream>
#include<string>
using std::cout;
using std::cin;
size_type length() const;
int main()
{
char a[100];
int i,x;
cout<<"Enter the string \n";
cin.getline(a,100);
cout<<a;
x=a.length();
cout<<x;
return 0;
}
What is wrong in the code above?
GCDEF
November 3rd, 2007, 06:25 PM
I'm sure your compiler has some idea.
a is a char array, not a struct or object, so it doesn't have any members such as length().
dcjr84
November 3rd, 2007, 08:32 PM
a as you have defined it is a character array, and not a string object. Therefore, you cannot use the length() member function of that class to determine its length.
If you are trying to find out how many characters were actually entered in a character array, you will need to do it a different way.
An example would be to loop through and count the number of characters individually until you reach the null terminator placed in the char array by getline()...
#include <iostream>
using namespace std;
int main()
{
char a[100];
cout << "Enter the string: ";
cin.getline(a, 99);
int count = 0;
for ( int i=0; (i < 100) && (a[i] != '\0'); i++)
{
count++;
}
cout << "The length was: " << count << endl;
return 0;
}
Also, a side note. If your char array is 100 characters, you can only read in 99 characters, because you need to leave the last element in the array open for the null terminator. If you don't, you will have an unterminated char array and will run into problems.
GCDEF
November 3rd, 2007, 08:59 PM
a as you have defined it is a character array, and not a string object. Therefore, you cannot use the length() member function of that class to determine its length.
If you are trying to find out how many characters were actually entered in a character array, you will need to do it a different way.
An example would be to loop through and count the number of characters individually until you reach the null terminator placed in the char array by getline()...
#include <iostream>
using namespace std;
int main()
{
char a[100];
cout << "Enter the string: ";
cin.getline(a, 99);
int count = 0;
for ( int i=0; (i < 100) && (a[i] != '\0'); i++)
{
count++;
}
cout << "The length was: " << count << endl;
return 0;
}
Also, a side note. If your char array is 100 characters, you can only read in 99 characters, because you need to leave the last element in the array open for the null terminator. If you don't, you will have an unterminated char array and will run into problems.
Or he could just use strlen.
kirtipriyanka
November 5th, 2007, 09:42 PM
Thanx a ton for the replies!
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.