c++ iterate through a vector of strings

c++ iterate through a vector of strings

Add iostream header file and change stdio to cstdio.

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

using namespace std;

int main() 
{
    vector<string> data={Hello World!,Goodbye World!};
    for (vector<string>::iterator t=data.begin(); t!=data.end(); ++t) 
    {
        cout<<*t<<endl;
    }
    return 0;
}

From the Open Watcom V2 Fork-Wiki on the C++ Library Status page:

<string>

Mostly complete. Although there are no I/O operators, all other member functions and string operations are available.

A workaround (besides implementing the << operator) would be asking the string instances for the C string:

for (vector<string>::iterator t = data.begin(); t != data.end(); ++t) {
    cout << t->c_str() << endl;
}

This of course only works as long as the strings dont contain zero byte values.

c++ iterate through a vector of strings

#include <iostream>
#include <vector>
#include <string>
 
int main()
{
   std::vector<std::string> data = {Hello World!, Goodbye World!};

   for (std::vector<std::string>::iterator t = data.begin(); t != data.end(); t++) {
    std::cout << *t << std::endl;
   }

   return 0;
}

Or with C++11 (or higher):

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

typedef std::vector<std::string> STRVEC;

int main()
{
    STRVEC data = {Hello World!, Goodbye World!};

    for (auto &s: data) {
        std::cout << s << std::endl;
    }

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *