I want to achive someting like this: User input values here for example 1,2,3
Your values: 1,2,3 [1,2,3 is inputed by user in one line]
and this values are pushed to array.I need check here if number is not bigger than max number for example 4 and isnt below 1.
I came up with this code. It takes msg to show for user and max num,but as you can see it only can return single value and i have no idea how to modify it to work as i discribed it.
const int getMultipleIntAboveZero(const std::string &msg,int maxNum){
int num;
std::cout<< msg;
while(!(std::cin>>num)|| num < 1 || num > maxNum){
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout<<"\nInvalid input. Try again: ";
}
return num;
}
CodePudding user response:
How can I get integer array inputted by user with commas?
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector< int > getMultipleIntAboveZero(std::string msg, int maxNum) {
std::istringstream iss (msg);
std::string unit;
std::vector<int> nums;
int num;
while(std::getline(iss, unit, ',')) {
num = std::stoi(unit);
if (num >= 1 && num <= maxNum) {
std::cout << num << '\n';
nums.push_back(num);
} else {
std::cout<<"Invalid input. Try again\n";
}
}
return nums;
}
int main()
{
printf("Your values: ");
std::string msg;
std::cin >> msg;
getMultipleIntAboveZero(msg, 4);
}