Cobold
Cobold

Reputation: 2613

c++ get multiple lines

I need a way to read the lines a user has pasted in the console. The user pastes it in this fashion:

1st line: n - number of lines except this one

2nd - nth: a string object

If I read it with cin, it reads the first line, exits the program, and the next lines is placed in the console input. With scanf I get similar results.

string s[100];

int N = 0;
scanf("%i", N);

for (int i = 0; i < N; i++)
{
scanf("%s", s);
}

Upvotes: 1

Views: 8059

Answers (2)

David G
David G

Reputation: 96875

It would be better if you used a std::vector<std::string> and use std::getline to extract the lines:

std::vector<std::string> lines;
std::string line;

while (std::getline(std::cin >> std::ws, line))
{
    if (!line.empty())
        lines.push_back(line);
}

Upvotes: 3

Arjen
Arjen

Reputation: 646

getline() will do the trick for you. Try this:

string lines[100];

int number = 0;
cin >> number;

for (int idx = 0; idx != number; ++idx)
{
    getline(cin, lines[idx]);
}

Note that you cannot read more than 100 lines this way. If you want to dynamically allocate an array of lines of size n, you can use the new operator.

Upvotes: 0

Related Questions