How to get multiple input from user in one line c++ - c++

5
1 2 3 4 5
the first line is how many input will user give.
and the second line is the input from the user. basically it's "c >> a >> b >> c;" but it's up to the user how many input they want.

The answer is quite simple. Read an int n indicating the number of items, then declare a std::vector<int> and read in n elements in a loop, pushing each onto the vector. This can be done either with an explicit for loop, or using STL functions.

It's simple to read input and store in std::vector. You can resize the vector to hold n elements by passing n to its constructor. Then you can read into the std::vector like you do for a normal array.
#include <vector>
#include <iostream>
int main()
{
int n;
std::cin >> n;
std::vector<int> v(n);
for (int i = 0; i < n; i++)
std::cin >> v[i];
for (int i = 0; i < n; i++)
std::cout << v[i] << std::endl;
}

I would be inclined to use a std::vector over any other data type.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector <int> xs;
int n;
std::cin >> n;
// method 1
std::copy_n( std::istream_iterator <int> ( std::cin ), n, std::back_inserter( xs ) );
// method 2
int x; while (n--) { std::cin >> x; xs.push_back( x ); }
In general, your goal should not be to do things “in one line”, but to do things correctly and succinctly, favoring correctness over terseness.

Related

"No match for operator>>" but I don't understand why. Could you explain me, please?

I have got the following code:
#include <iostream>
#include <vector>
using namespace std;
vector<int> Reversed(const vector<int>& v){
//vector<int> v; //[Error] declaration of 'std::vector<int> v' shadows a parameter
int z; vector<int> copy; vector<int> working;
working = v;
z = working.size();
int i;
for (i = 0; i<=z; i++){
working[i] = working[z];
copy.push_back(working[i]);
}
return copy;
}
int main() {
vector<int> v;
cin >> v; /*[Error] no match for 'operator>>' (operand types are 'std::istream'
{aka 'std::basic_istream<char>'} and 'std::vector<int>')*/
cout << Reversed(v);
return 0;
}
Please, explain to me why I am getting this error on line 18:
no match for operator >>`
P.s.: const & i is a prerequisite task, I cannot change it. I just need an upside-down copy of this vector.
It looks like you are asking the user to enter a list of numbers. std::cin (or just cin, since you've got use namespace std;) doesn't know how to receive a list of integers and turn that into a vector<int> for you.
If you want to receive a vector from user input, I would suggest you ask the user for a list of numbers, something like:
// replace VECTOR_LENGTH
for (int i = 0; i < VECTOR_LENGTH; i++) {
int num;
cin >> num;
v.push_back(num);
}
You are trying to read the whole vector in one go when you do this cin >> v;. You probably want to read one element at a time, like:
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
// read five integers from stdin
const int n = 5;
vector<int> v(n);
for(int i = 0; i < n; ++i)
cin >> v[i];
for(int i = 0; i < n; ++i)
cout << v[i] << "\n";
return 0;
}
Output:
0
1
2
3
4
Or use std::vector::push_back as in #ajm answer.

did in i need in my c++ code to use vectors or learn STL

i need to initialize my code during runtime the program is searching for how many times is the number in multiplication table
#include <iostream>
using namespace std;
int main()
{
int x = 0, n = 1 , count=0 ;
cin >> n>>x;
int arr[n][n];
for (int i = 0; i <n-1 ; i++) {
for (int j = 0; j <n-1 ; j++) {
cin >> arr[i][j];
if(arr[i][j]==x)count++;
}
}
cout<<count;
}
because i am getting error
did in i need in my c++ code to use vectors or learn STL?
The answer depends on your objective.
If you want to accomplish a programming task at hand in the most expedient manner, use std::vector.
If you want to learn how to manage allocation and dealloction of dynamic memory, learn about new and delete and use them instead of int arr[n][n];
I think by multiplication table you mean to say matrix.
For this particular problem you don't need even the matrix. You can just do by using a temporary variable. Something like this:
#include <iostream>
int main() {
int n, x, count = 0, tmep;
std::cin >> n >> x;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
std::cin >> temp;
if (temp == x) ++count;
}
std::cout << count;
}
You aren't getting proper answer probably because you are not reading the complete matrix. Your loops run from i = 0 to i < n - 1 (same for j). You need to either change < to <= or n - 1 to n.
If you need to re-use the inputted matrix, then probably an approach like this will be good:
#include <iostream>
#include <vector>
int main() {
int n, x, count = 0;
std::cin >> n >> x;
std::vector<std::vector<int>> mat(n, std::vector<int>(n));
for (auto &row : mat)
for (auto &ele : row) {
std::cin >> ele;
if (ele == x) ++count;
}
std::cout << count;
}
In any case something like arr[n][n] is not recommended as variable-length arrays are not supported by the standard itself, although some compilers like g++ do so.

Why can't I directly read from cin into an array index?

I'm trying to learn C++ on HackerRank, but I've encountered a weird situation in one of the exercises given.
The exercise is to read in a list of numbers and print them out reversed. However, my code appears to spit out garbage values for one of the test cases.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int temp;
int *arr = new int[n]();
cin >> n;
for (int i = 0; i < n; i++) {
// This works
/*
cin >> temp;
arr[i] = temp;
*/
cin >> arr[i]; // But this doesn't
}
for (int j = n - 1; j >= 0; j--) {
cout << arr[j] << " ";
}
return 0;
}
The input for the offending test case was a bit long, so I put it into a pastebin: https://pastebin.com/VCjciUet
When reading directly from cin (i.e. cin >> arr[i]), the output was as follows:
6002 {...truncated...} 8084 3909 5426 808465952 942682421 540227121 824194360 909189169 959526176 825243441 540619576 891304241 842539056 825374240 960050744 540619575 958412851 892805173 808722489 960050720 959460408 540553528 891302967 926425141 909718304 859189816 540226104 941634871 842342452 808662048 809054519 540160311 891303224 875634745 808466464 876034355 540423990 958412593 925966391 892613920 808662321 540422194 958411319 840972592 876159030 825374752 926364977 540553273 874526514 924858416 876093495 875770144 858928434 540030771 941634360 875831350 959788576 842413112 540095796 874525239 959651892 959723040 842018869 540096056 874525751 540424244 908079412 859185206 960051232 875901235 540028978 924857392 926228532 808925216 959526195 540095028 908079408 960045108 825308448 942684471 540096306 840971065 858857522 892739637 926103072 842150707 540291892 941634608 875700275 876033824 909457721 540160822 824194100 859250740 825766688 875706678 540356912 840972345 875962418 808923936 825242421 540226869 924856887 892608560 825439520 909130037 540620083 857749813 943267896 943011360 925972531 540094773 840971319 825368627 808728608 808728374 540161588 908079666 842080313 909652512 876032561 540554040 941635895 808788017 808858144 825505842 540555320 840972344 892870710 825832480 842150450 540422199 874526264 909713464 892482592 926366005 540094769 924857396 842407992 892811040 875705656 540619320 908080177 857748528 875962423 909652256 892745779 540226866 540423479 540554291 540619064 540096820 891302709 926294071 808597792 892679200 909522745 540555315 924858417 891303988 909451315 859054128 909523232 942684473 540031287 857748019 808984630 959591456 925971510 540619057 958411316 909385783 825506080 858927392 808597810 540357168 908080176 909385778 858993440 875705632 892679737 540422960 924858672 875896883 875967520 842283065 540358967 908079669 859381815 943273248 825439288 540422969 908081465 926162994 925905440 959591735 540094512 824193335 859054130 875896889 876098848 959459892 540358706 540028977 2139 7277 9113 6303 924 7608 749 6043
However, the output was accurate (the entire list of numbers reversed) when I used a temporary variable first.
Why is this so?
It's so because you didn't listen to your compiler:
main.cpp: In function 'int main()':
main.cpp:13:27: warning: 'n' is used uninitialized in this function [-Wuninitialized]
int *arr = new int[n]();
^
Writing low-level code is prone to mistakes like those. Prefer high-level library features that prevent them. If your goal was to read a collection of numbers and print them out, it can be done without any loops at all:
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
std::vector<int> v;
std::copy(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(v)
);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout));
}
This code will simply read until the numbers end. If you want to read the count of them first, you still should check whether they don't end beforehand. One issue with learning via things like HackerRank is that they completely omit learning input sanitization and error handling, which are crucial in real-world coding.
Turn on the compiler warnings:
source>:13:24: error: 'n' is used uninitialized in this function [-Werror=uninitialized]
13 | int *arr = new int[n]();
|
n was uninitallized when you used it. Also, you never deleted the array. Yes, the OS will clean up after you, but it is best to free the memory you allocated. Here's the fixed version:
#include <iostream>
int main() {
int n;
std::cin >> n;
int *arr = new int[n]();
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
for (int j = n - 1; j >= 0; j--) {
std::cout << arr[j] << " ";
}
delete[] arr;
return 0;
}
Having said that, it's probably a better idea to use std::vector and std::size_t. Here's how you go about doing that:
#include <iostream>
#include <vector>
int main() {
std::size_t n{};
std::vector<int> vec{};
std::cin >> n;
vec.resize(n);
for (auto&& elm : vec)
std::cin >> elm;
for (auto rit = vec.crbegin(), rend = vec.crend(); rit != rend; ++rit)
std::cout << *rit << ' ';
return 0;
}
With a little help from Boost this example can be shorter.
#include <iostream>
#include <vector>
#include <boost/range/adaptor/reversed.hpp>
int main() {
std::size_t n{};
std::vector<int> vec{};
std::cin >> n;
vec.resize(n);
for (auto&& elm : vec)
std::cin >> elm;
for (auto&& elm : boost::adaptors::reverse(vec))
std::cout << elm << ' ';
}

How to insert the range of numbers to an array by iterating through it?

I am making a program, in which I need to iterate the numbers, starting from 1 to num then put the value of that array {1...num} to a variable that can be called in the for loop.
This is where I am at.
int main()
{
int num = 0;
cin >> num;
for (int i = 1; i <= num; i++)
{
procnum[i];
}
}
I need procnum[num] to have a value like ...
int procnum[num] = {1,2,3...num};
If you can use std::vector and std::iota, this is just two line code.
No need to for(index) loop the array. See live example here
#include <vector> // std::vector
#include <numeric> // std::iota
std::vector<int> procnum(some_size);
std::iota(procnum.begin(), procnum.end(), 1);
In C++11, no need to even write a loop, unless you need to do error checking (e.g. check that reading input succeeded, or that the input value is valid).
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main()
{
int size;
std::cin >> size;
std::vector<int> procnum(size);
std::iota(procnum.begin(), procnum.end(), 1); // starting value is 1
// output vector to demonstrate it is populated
std::copy(procnum.begin(), procnum.end(), std::ostream_iterator<int>(std::cout," ");
std::cout << "\n";
}
Before C++11, there was no algorithm std::iota(), but it is possible to use std::generate() and a simple functor to achieve the same effect.
you can use std::vector to create dynamic arrays:
#include <iostream>
#include <vector>
int main() {
int size;
std::cin >> size;
std::vector<int> procnum(size);
for (int i = 0; i < size; ++i) {
procnum[i] = i + 1;
}
}
you shouldn't use namespace std; - read here why.

Printing an array in reverse

Task
You'll be given an array of N integers and you have to print the integers in the reverse order.
Constraints
1<=N<=1000
1<=A_i<=10000, where A_i is the ith integer in the array.
Input
4
1 2 3 4
Output
4 3 2 1
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N, y; //declaring N as the length of array
cin >> N; //intakes the length as an input
if (N>=1 && N<=1000){ //checks whether the length satisfies the rules
int a[N]; // makes an array containing N elements
for (int x =1; x<N; x++){ //starts transcription on the array
cin>>y; //temporarily assigns the input on a variable
if (y>=1&&y<=10000){ //checks if the input meets rules
a[x]=y; //copies the variable on the array
}
}
for (int z = N; z>1; z--){ //runs a loop to print in reverse
cout<<a[z]<<endl;
}
}
return 0;
}
Problem
Obtained output is
-1249504352
3
2
Indicating an error in transcription.
Question
Can somebody please tell me where I am making a mistake? Secondly, is it possible to directly check whether an input is meeting requirement rather than temporarily declaring a variable for it?
Here is a solution in idiomatic c++11, using std::vector, which is a dynamically resizable container useful for applications like this.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
int size;
std::cin >> size; // take in the length as an input
// check that the input satisfies the requirements,
// use the return code to indicate a problem
if (size < 1 || size > 1000) return 1;
std::vector<int> numbers; // initialise a vector to hold the 'array'
numbers.reserve(size); // reserve space for all the inputs
for (int i = 0; i < size; i++) {
int num;
std::cin >> num; // take in the next number as an input
if (num < 1 || num > 10000) return 1;
numbers.push_back(num);
}
std::reverse(numbers.begin(), numbers.end()); // reverse the vector
// print each number in the vector
for (auto &num : numbers) {
std::cout << num << "\n";
}
return 0;
}
A few things to note:
using namespace std is considered bad practice most of the time. Use (e.g.) std::cin instead for things which come from the std namespace.
numbers.reserve(size) is not necessary for correctness, but will make the program faster by reserving space in advance.
for ( auto &num : numbers ) uses a range-based for loop, available in c++11 and later versions.
You could make your for loop indices go from high to low:
for (int i = N-1; i > 0; --i)
{
std::cout << a[i] << "\n"; // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";
This would apply with std::vector as well.
With std::vector, you can use a reverse iterator. There are other techniques available (as in other answers).