Advertisement

strings with vectors??

Started by May 01, 2001 03:45 PM
2 comments, last by cMADsc 23 years, 9 months ago
I am still new to vectors, although ,I am trying to input some strings and then sort them. Here is an example: reading in some names then sorting the names. I have already done this by making an array of structs, even by using an array of classes. Here is an example: struct { char mybuffer[99]; } buffer[99] for (int i = 0; i < num; i++) cin.getline >>(buffer.buffer, 98); . . . Then I used a bubble search to sort it. But I want to use vectors so I rewrote the program using vectors but the vectors were only reading in one char not a whole string. Any suggestion on how to read in a string into vectors? Thx. ----------------------------- "There are ones that say they can and there are those who actually do." "...u can not learn programming in a class, you have to learn it on your own." Edited by - cMADsc on May 1, 2001 4:48:18 PM Edited by - cMADsc on May 1, 2001 6:11:23 PM
-----------------------------"There are ones that say they can and there are those who actually do.""...u can not learn programming in a class, you have to learn it on your own."
I''m surprised your previous code worked.

Is this what you want?

    typedef struct _charBuffer {    char buffer[99];  } charBuffer;  const int size = 3;  vector <charBuffer> buffer(size);  ...  // BUG: executes (buffer.size() + 1) times  for (int i = 0; i < buffer.size(); i++)  {    cin.getline(buffer[i].buffer, 98);    ...  }  


This has a bug. It asks for (buffer.size() + 1) number of input. I don''t know why. Never had much success with cin.getline().

Jinushaun
Advertisement
How about this code:
  #include <iostream>#include <string>#include <vector>#include <algorithm>#include <iterator>using namespace std;int main(){  vector<string> v;  // ask for 10 strings, insert them into vector  for (int i=0; i<10; ++i)  {    string str;    cin >> str;    v.push_back(str);  }  // sort the strings  sort(v.begin(), v.end());  // print the sorted vector  copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));  return 0;}  


Edited by - JungleJim on May 2, 2001 5:24:27 AM
Yeah, why don''t you use std::string? (see JungleJim''s code) unless it''s a major inconvenience to change all your code to use that, I don''t see why not. Btw, my code sample didn''t use stl string for that reason.

Jinushaun

This topic is closed to new replies.

Advertisement