STL >> string >> the [] operator to find the n't

Write here if you have problems with your C++ source code

Moderator: Board moderators

STL >> string >> the [] operator to find the n't

Postby smilitude » Fri Sep 08, 2006 1:41 am

I saw in the ref that there is something like this in <string>
reference operator[](size_type n) Random Access Container Returns the n'th character.


can you tell me how to use it,
i tried as following but it showed me compile error!
Code: Select all
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> a;
    string input;
    int len;
    char ch;
   
    cin>>input;
    a.push_back(input);
    len = a.size();
    for(int i=0;i<len;i++) {
        ch = a[i];
        cout<<ch;
    }
    cout<<endl;
return 0;
}
fahim
#include <smile.h>
User avatar
smilitude
Experienced poster
 
Posts: 137
Joined: Fri Jul 01, 2005 12:21 am

Postby Krzysztof Duleba » Fri Sep 08, 2006 3:02 am

Hint: learn how to read compiler messages, this one should be fairly straightforward.

Hint 2: does that reference say anything about push_back method?
For millions of years, mankind lived just like the animals. Then something happened which unleashed the power of our imagination. We learned to talk and we learned to listen...
User avatar
Krzysztof Duleba
Guru
 
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland

Postby smilitude » Fri Sep 08, 2006 4:40 am

thanks Krzysztof! I got it! :oops:
i was trying to do this in wrong way ...

Code: Select all
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> a;
    string input;
    int len;
    char ch;
   
    cin>>input;
    a.push_back(input);
    len = a[0].size();
    for(int i=0;i<len;i++) {
        ch = a[0][i];
        cout<<ch;
    }
    cout<<endl;
    //system("pause");
return 0;
}

fahim
#include <smile.h>
User avatar
smilitude
Experienced poster
 
Posts: 137
Joined: Fri Jul 01, 2005 12:21 am

Postby Krzysztof Duleba » Fri Sep 08, 2006 12:07 pm

Ouch, I thought you were pushing back to a string (which shouldn't work, so I didn't even bother to compile that code), but now I see you called push_back on a vector, which is perfectly valid.

I'm glad you were able to resolve it on your own.
For millions of years, mankind lived just like the animals. Then something happened which unleashed the power of our imagination. We learned to talk and we learned to listen...
User avatar
Krzysztof Duleba
Guru
 
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland


Return to C++

Who is online

Users browsing this forum: No registered users and 1 guest