iterate through a vector of strings

I'm trying to create a vector by a user entering words, storing these words into a vector, and then outputting them. What is the simplest way to do this at a beginner level without using any arcane libraries? (This is with C++11).

Should I use sstream?

This is my current and totally incorrect code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main() {
	vector<string> myVector;
	string userInput = "";

	cout << "Enter some words for the vector: ";
	while (cin >> userInput) {
		myVector.push_back(userInput);

		for (int i = 0; i < myVector.size(); i++) {
			cout << myVector.at(i) + " " << endl;
		}
	}

	system("pause");

	return 0;

}
Last edited on
Hi,

A few things:

The for loop needs to be outside the loop that collects the input.

std::cin only reads up to the first space, so it will only do 1 word. You can use std::getline instead.

You could have some sentinel value to end the loop, say "999"

The size functions return a type std::size_t, so to avoid an implicit cast, do the for loop like this:

for (std::size_t i = 0; i < myVector.size(); i++) {

There is another way to do the for loop like this, called a range based for loop :

1
2
3
for ( const auto& item : myVector) {
   std::cout << item << "\n";
}


Even better, like this, with a forwarding reference:

1
2
3
for ( auto&& item : myVector) {
   std::cout << item << "\n";
}


This last version works for const, non const, lvalues, rvalues , all of which which might be too advanced right now, but there you go :+) It is actually the safest and best way to do it .

Note that none of this uses any libraries, it's all pure c++11 language.
Last edited on
Topic archived. No new replies allowed.