By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,404 Members | 927 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,404 IT Pros & Developers. It's quick & easy.

string class ( size function)

P: 65
in the code below, why size of the B string is wrong?

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3.  
  4.  
  5. int main()
  6. {
  7.         string A("abcdef");
  8.         string B;
  9.  
  10.         cout<<"A.size(): "<<A.size()<<endl;
  11.         cout<<"B.size(): "<<B.size()<<endl;
  12.  
  13.         for(int i=0;i<A.size();i++)
  14.                 B[i]=A[i];
  15.  
  16.         cout<<"B.size(): "<<B.size()<<endl;
  17.  
  18.         return 0;
  19. }
Jun 5 '07 #1
Share this Question
Share on Google+
3 Replies


DeMan
100+
P: 1,806
Please provide more information. What are you getting for size (0 I assume?) and what are you expecting (5 probably?)
Jun 5 '07 #2

gpraghuram
Expert 100+
P: 1,275
Hi,
U will get the size of string B as zero because while initialization u havent given any size and you are copying value to it like array(What u are doing is array over-write)
You have to either specify the size during init or use assign method to copy the value
like B.assign("cc")


Raghuram
Jun 5 '07 #3

P: 65
for DeMan:
i am expecting 5 but i am getting 0.

for gpraghuram:
overloaded assignment operator does not do the same thing
with assign function?
Jun 5 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.