How do I store a user input into an array?

How do I store a user input into an array? Please try to explain simply as I've only just begun learning how to code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main()
{

    string word4;


    cout << "Please enter a country: " << endl;
    cin >> word4;

}


For example if someone wants to put Sierra Leone, it would only store Sierra.
Last edited on
This question has nothing to with arrays.

If you want to read an entire line into a single std::string, rather than just space-delimited parts of it, use the getline() function:

http://www.cplusplus.com/reference/string/string/getline/
Last edited on
Normally you access an array by an index.
Lets say you have an array of int like this:
int array[5];
Now you store the value 1 at the first location like this:
array[0] = 1; Please note that the first index is 0 and the last index is 4.
Getting user input that includes whitespace requires using getline. For C strings (char arrays) or std::string.

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

int main()
{
   const int SIZE { 80 };

   char country_cstr[SIZE];

   std::cout << "Enter the country name: ";
   std::cin.getline(country_cstr, SIZE);

   std::cout << "You entered: " << country_cstr << "\n\n";

   std::string country_str;

   std::cout << "Enter the country name: ";
   std::getline(std::cin, country_str);

   std::cout << "You entered:" << country_str << '\n';
}

Enter the country name: United Kingdom
You entered: United Kingdom

Enter the country name: Sierra Leone
You entered:Sierra Leone
Topic archived. No new replies allowed.