CS 702 - Operating Systems - Fall 2007
Standard Template Library


Loyola College > Department of Computer Science > Dr. James Glenn > CS 702 > Examples and Lecture Notes > Standard Template Library

strings_and_vectors.cpp

#include <string>
#include <iostream>
#include <sstream>
#include <vector>

int main()
{
  // read one line of input (newline is read but not stored in input)

  std::string input;
  std::getline(std::cin, input);

  // stick input into a stream
  
  std::stringstream stream;
  stream << input;

  // create vector to hold all the individual tokens

  std::vector< std::string > tokens;

  // put each token in the stream at the end of the vector

  std::string tok;
  while (stream >> tok)
    tokens.push_back(tok);

  // output all the C++strings in the vector

  for (int t = 0; t < tokens.size(); t++)
    std::cout << tokens[t] << std::endl;

  // convert from a vector of C++ strings to an array of C strings

  char **cstrings = new char*[tokens.size()];
  for (int t = 0; t < tokens.size(); t++)
    {
      cstrings[t] = new char[tokens[t].length() + 1];
      strcpy(cstrings[t], tokens[t].c_str());
    }

  // output all the C strings
  
  for (int t = 0; t < tokens.size(); t++)
    printf("%s\n", cstrings[t]);
}
This code can also be downloaded from the file strings_and_vectors.cpp.