String Length Error

Hi,
I'm trying to find the length of a string, my program runs fine but always tell the length 0 ..

In the condition of for loop if I write Mystr[k]!='\0' the program crashes..

Thanks in advance to helping hands


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>
#include <string>
using namespace std;
int main ()
{
	string Mystr;
	cout<<"Enter a string: ";
	getline(cin,Mystr);
	
	int count =0;
	for (int k=0; Mystr[k]='\0'; ++k)
	{
		count++;
	}
	cout<<"Length: "<<count<<endl;
	//cin.ignore();
	return 0;
}
Last edited on
My compiler wrote:
warning: suggest parentheses around assignment used as truth value [-Wparentheses]

In the loop condition you are using = instead of ==.

There is a much easier way to get the length, you can just call Mystr.length() (or Mystr.size()) to get the length of the string.

http://www.cplusplus.com/reference/string/string/length/
Last edited on
1
2
3
4
5
        string Mystr;
	cout << "Enter a string: ";
	getline(cin, Mystr);

	cout << endl <<  Mystr.length() << endl;
ButchCavendish wrote:
In the condition of for loop if I write Mystr[k]!='\0' the program crashes..

I'm not sure if Visual C++ has fixed this bug in the latest versions but I know their debugging code used to complain about accessing str[str.size()] even though this has been explicitly allowed since C++11.
Last edited on
Thanks Buddy.. @Peter87
I've tried the same program on eclipse latest version .. it runs fine.. but why it crashes on visual studio 2010 ?? Any Idea ?
Topic archived. No new replies allowed.