string question

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Aug 2008
Posts: 87
Reputation: freelancelote is an unknown quantity at this point 
Solved Threads: 2
freelancelote's Avatar
freelancelote freelancelote is offline Offline
Junior Poster in Training

string question

 
0
  #1
Dec 14th, 2008
This's got probably an easy answer but it's been puzzling me a few hours already.
The code below declares a string object and fills it character by character. I can print every single character (line 16) but I can't print the string as a whole (line 19).
Could anybody tell me why is that so and how to fix it, please?

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. string a;
  8.  
  9. cout << "String a is: " << a << endl; //Nothing expected, fine
  10. char tmp= 100;
  11. for (int i=0; i<10; i++)
  12. {
  13. a[i]= tmp;
  14. tmp++;
  15. }
  16. for (int i=0; i<10; i++)
  17. cout << a[i];
  18.  
  19. cout << "\na: " << a << endl;
  20. return 0;
  21. }
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 182
Reputation: mrboolf will become famous soon enough mrboolf will become famous soon enough 
Solved Threads: 18
mrboolf mrboolf is offline Offline
Junior Poster

Re: string question

 
1
  #2
Dec 14th, 2008
Change a[i]= tmp; with a += tmp; .
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,770
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 743
Team Colleague
Narue's Avatar
Narue Narue is online now Online
Code Goddess

Re: string question

 
2
  #3
Dec 14th, 2008
>string a;
This is an empty string.

>a[i]= tmp;
a[i] doesn't exist. a is still an empty string. The subscript operator does not change the size of a collection.
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC