str.length() is always giving 0

Jan 30, 2013 at 5:14pm
In this code-
#include <iostream>
#include<cstdlib>
#include<cstring>
#include<conio.h>

int main()
{
std::string a="";
char c;
for(int i=0;i<1000;i++)
{
c=getch();
if(c=='\r')
break;
std::cout<<"*";
a[i]=c;
}
int d=0;
d=a.length();
std::cout<<d;
std::cout<<a;
return 0;
}

The value of d is always 0, and the 'std::cout<<a' code gives no output. Why? Please help!
Jan 30, 2013 at 5:23pm
a[i]=c;

try

a = a + c
Jan 30, 2013 at 5:25pm
replace a[i]=c; with a+=c; (or make your string 1000 characters long from the start, it's empty right now)
Jan 30, 2013 at 5:38pm
Thanks, it works. But what confusing me is that, in my wrong method, if I enter a string, say "abcd" and we compare it with another string b(std::string b="abcd") by->a==b, i am actually getting a return value-0, which means that the strings are same. But as I said, when I am printing a i get nothing. How is that happening?
Jan 30, 2013 at 5:47pm
A return value of zero means they are not the same.

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
#include <iostream>
#include <cstdio>
#include <cstring>

int main()
{
	std::string a="";
	std::string b = "abcd";
	char c;
	for(int i=0;i<1000;i++)
	{
		c=getchar();
		std::cin.ignore();
		if(c=='.')
			break;
		std::cout<<"*";
		a += c;
	}
	int d=0;
	d=a.length();
	std::cout<<"String length is " << d<<std::endl;
	std::cout<<"String is " << a <<std::endl;

	std::cout << (a == b) <<"\n";

	return 0;
}


a
*b
*c
*d
*.
String length is 4
String is abcd
1
Jan 30, 2013 at 5:56pm
What?????..... but in Turbo C++ a return value of 0 meant that the arrays are same. I didn't know that in the GCC compiler it's just the opposite! Thanks for enlightning me @Smac89 :-D
Jan 30, 2013 at 7:05pm
The return value of operator == has type bool. It is true when they are equal and it is false when they are not equal. If you convert bool to int (such as by printing it without boolalpha), false becomes 0 and true becomes 1. This is the same in any compiler.
Last edited on Jan 30, 2013 at 7:06pm
Jan 30, 2013 at 7:43pm
Sucho might be thinking of strcmp, which returns zero when two char arrays are equal.
Jan 31, 2013 at 11:37am
Yup, just found out that strcmp() returns 0 when the strings are same. That's why I thought that similiarity returns a value '0'. Its different from the '=='. Thanks guys!!!
Topic archived. No new replies allowed.