I'm trying to improve my C++ by doing some Google Kick Start but I can't begin my program because I can't get N inputs. I come from python where this would be exceedingly easy with input().split(), but I have no idea how to do this in C++. I tried googling to find an answer but I cant word my question correctly to where I find the answer. Here is my current code:
#include <iostream>
int main() {
int t = 0;
std::cin >> t;
for (int i = 0; i < t; i++) {
int n = 0, int k = 0;
int a[1000];
std::cin >> n >> k;
std::cin >> a;
}
}
, where T is the number of test cases, N is the number of items in the list, K is an argument used to calculate the answer for the contest, and A is the array of N length used to store the values. (The contest is already over, I'm not cheating) It would be nice if someone could help me understand how exactly std::cin works. At first I thought it would be exactly the same as python's input(), but it's different. Thanks.
First of all, there's a typo in your variable declaration. You should only write the type once in the statement, so it should be int n = 0, k = 0;
.
The extraction ( >>
) operator only reads single numbers. To take input into an array, you can just write a loop:
int a[1000];
for (int i = 0; i < n; i++)
{
std::cin >> a[i];
}
This simply reads n
numbers and stores them into successive elements in a
.
If you want to be fancy, you can use stream iterators:
std::copy_n(std::istream_iterator<int>(std::cin), n, a);
std::istream_iterator<int>(std::cin)
constructs a stream iterator which extracts int
s from std::cin
. std::copy_n
then copies n
numbers from the stream iterator to a
. You need to #include <iterator>
and #include <algorithm>
in order to use this. You'll probably want to stick with the loop if you don't understand this yet.
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.