Attempting to store user input into array

How do I read user input line by line and store that user input into an array?

In other words, storing "Apples raw, 110, 50.6, 1.2, 1.0" into a char array and that whole line is index 0. Then index 1 will be "Bananas,225, etc"

Here is the user input:

Apples raw, 110, 50.6, 1.2, 1.0

Bananas, 225, 186, 6.2, 8.2

Bread pita whole wheat, 64, 134, 14, 22.6

Broccoli raw, 91, 21.9, 2.8, 6.3

Carrots raw, 128, 46.6, 2.6, 3.3

Upvotes: 1

Views: 91

Answers (1)

tresz
tresz

Reputation: 86

For writing user input line by line you could use a getline() function. It reads a line untill it encounters a delimiter which is by default a newline character "\n".

Example:

#include <iostream>

int main()
{
    std::string yourArray[5];

    for(int i=0; i<5;i++)
    {
        getline(std::cin, yourArray[i]);
    }

    std::cout << std::endl;

    for(int i=0; i<5; i++)
    {
        std::cout << yourArray[i] << std::endl;
    }
}

input:

Apples raw, 110, 50.6, 1.2, 1.0
Bananas, 225, 186, 6.2, 8.2
Bread pita whole wheat, 64, 134, 14, 22.6
Broccoli raw, 91, 21.9, 2.8, 6.3
Carrots raw, 128, 46.6, 2.6, 3.3

output:

Apples raw, 110, 50.6, 1.2, 1.0
Bananas, 225, 186, 6.2, 8.2
Bread pita whole wheat, 64, 134, 14, 22.6
Broccoli raw, 91, 21.9, 2.8, 6.3
Carrots raw, 128, 46.6, 2.6, 3.3

Upvotes: 2

Related Questions