Create an array of strings via cin or getline

Ok so I searched this site, and google string arrays, but I couldn't find anything on how to create an array to accept string input. In other words the strings are unknown, until the user inputs them..

so code would say input a name..user enters Tom, and its inserted into the array.. and if another name is entered ..lets say Lisa..Lisa is added to the array..so now in the array we have tom and Lisa..

Everything I read only shows the array already having the strings declared...


My best guest is

1
2
3
string n;
string name[n]={};

to declare an array, it needs an unsigned integral type for the size, not a string or something.

The best way is to use std::vector<std::string> and use
push_back() to add an element into the vector.

A vector grows automatically so you won't need to limit yourself to a fix sized array.

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

int main()
{
    using namespace std;
    
    vector<string> names;
    string tempName; // temporary var to hold the current name
    
    while( cin >> temp )
        names.push_back( tempName ); // add tempName to the end of the vector

    // you can query the size of a vector using .size() method
    for( size_t i = 0; i < names.size(); ++i ) {
        // you can use operator[] just like a normal array to get
        // an element of a vector
        cout << "Hello, " << names[ i ] << "!\n";
    }
}
Last edited on
thank you..That worked..
Topic archived. No new replies allowed.