Home > Software engineering >  Multiple inputs in one line in C
Multiple inputs in one line in C

Time:12-01

I've newly started learning C and am stuck with this problem. I need to insert a (user inputted) number of elements in a single line with space separation. If the number of elements was known, I could just write cin >> var1 >> var2 >> ... >> varN;. But how do I do it with any number of elements (loop maybe)?

This is what I'm trying to do:

#include<bits/stdc  .h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int arr[n];
    for (int i=0; i<n; i  ) {
        //stuck here
    }
}

I could have written cin >> arr[i]; and proceeded, but that would require the user to press enter after every input, which I cannot do due to the question's restrictions. How do I write the code so that all my input for array elements can be given in a single line?

PS: I've seen several similar questions already answered on the site, but most of them involve implementations using vectors or are beyond my current level of understanding. A simpler solution will be appreciated.

CodePudding user response:

cin>>arr[i] does not require the user to press enter after every input. You just need to give whitespace between the integer inputs. It will scan the array normally.

CodePudding user response:

You would probably want to replace your array with a std::vector to make it resizable in run time. If you do like in your example the program will not compile because n is not known when the program is built.

Here is a simple example

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    int n = 0;
    cin >> n;
    vector<string> arr; // A vector (ie kind of a variable sized array)
    for (int i=0; i<n; i  ) {
        string str;
        cin >> str; // Read a word
        arr.push_back(str); // Add a string to the vector
    }

    // To use the data
    for (int i = 0; i < arr.size();   i) {
        cout << arr.at(i) << "\n"; // Print value of vector
    }
    // or like this
    for (auto str: arr) {
        cout << str << "\n";
    }
}
  • Related