简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM