Search code examples
c++stringloopsvectorsubstr

C++ - Storing user input string separated by commas into vector


I have a code written that performs this task to a certain extent. But, I would like to how to alter my code so that I can store as many string inputs the user wants to enters into the vector.

Here is my code:

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

int main ()
{
string input = "";
cout << "Input: ";
cin >> input;
string a,b;

for(int i = 0; i<input.size(); i++)
{
    if(input.at(i)==','){
        a=input.substr(0,i);
        b=input.substr(i+1);
    }
}

vector<string> objects;
objects.push_back(a);
objects.push_back(b);

for (int k = 0; k < 2; k++) {
    cout << objects[k] << endl;
}

return 0;
}

So far, it can only recognize and store two inputs separated by commas. I am very new to coding so could someone show me a way to make this into a loop and take in as many inputs as the user enters?

Thank you.


Solution

  • You need to change your code in order to work for any number of user input. The logic is to push every sub string between the commas into vector.

    vector<string> objects;
    
    for(int i = 0,j=0; i<input.size(); i++)
    {
        if(input.at(i)==',' || input.at(i)=='\0'){
            objects.push_back(input.substr(j,i-j)); //pushing the sub string
            j=i+1;
        }
    }
    

    In order to print the vector first you have to find the size of the vector,then simply iterate over to print it.

    //display
    
    int l=objects.size();
    for (int k = 0; k < l; k++) {
        cout << objects[k] << endl;
    }
    

    Note: If you want your code to work for strings with spaces in between , for example: a ,b ,c ,d then use getline(cin,input); to take input from user.