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;
}
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);
}
Related
When I input [1,0,0,1,0] I get output with 1 0 0 1 0 0, I don't know why there is an extra zero and why the while loop doesn't terminate after ].
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string str;
std::istringstream is;
std::vector<int> numbers;
std::getline(std::cin, str);
is.str(str);
char ch;
is >> ch;
while (!is.eof())
{
int num;
is >> num >> ch;
numbers.push_back(num);
}
for (auto num : numbers)
std::cout << num << " ";
std::cout << std::endl;
return 0;
}
Change the while loop part will get expected behavior:
int num;
while (is >> num >> ch) {
numbers.push_back(num);
}
The eof check is misused here, so the last character read failed and get a default number 0. Read this answer for more details:
https://stackoverflow.com/a/4533102/1292791
This code calculates the average from user that user inputs integer until user inputs "666" integer. However, I want to make it stop when the user just presses the enter key. How can I achieve this?
#include <iostream>
using namespace std; //s
int main()
{
int total = 0, counter = 0, number, average;
do
{
cin >> number;
if(number == 666) //what should i do to make enter button instead of 666?
{
average = total / counter;
cout << average;
return 0;
}
total = total + number;
counter = counter + 1;
} while(1);
return 0;
}
Sadly, you cannot check that easily if the <ENTER> button has been pressed. cin reads formatted input (numbers in your case) and ignores everything else (including whitespaces, like newline). A solution to your problem is to read a whole line and extract the numbers from it:
#include <iostream> // cin, cout
#include <sstream> // istringstream
#include <string> // getline
int main()
{
// Reading a line from the standard input to the variable 'line'.
std::string line;
std::getline(std::cin, line);
// The easiest way to get the numbers from 'line' is to wrap it in an
// 'istringstream'. Now, you can use 'iss' just like 'cin'.
std::istringstream iss{line};
double total = 0.0;
double counter = 0.0;
for (double number; iss >> number; ++counter) {
total += number;
}
std::cout << "Avarage: " << total / counter << '\n';
return 0;
}
I have been found the solution:
note that I use Code::Blocks compiler and I had to make a adjustment.
Settings> compiler > tick on the """have g++ follow the c++11 ISO C++ language standard [-std=c++11]""" box and click OK.
solution is below:
#include <iostream>
#include <string>
using namespace std;
int main() {
float c = 0, sum = 0;
string input;
while (true) {
cout << "input number:";
getline(cin,input);
if (input == "") {
cout << "average:" << sum / c << endl;
break;
}
sum += stof(input);
c++;
}
return 0;
}
int x;
if(cin >> x)
cout << "True" << endl;
else
{
cin >> x;
}
It supposes to let me enter the number again but it's end the program without taking the number again
A simple solution is to get the input as string, use regex to check if it's a number and if it is convert it to an int, otherwise ask for input again. Here's an example:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::regex rx(R"((?:^|\s)([+-]?[[:digit:]]+(?:\.[[:digit:]]+)?)(?=$|\s))");
std::string line;
int n;
while ( std::getline(std::cin, line) ) {
if ( std::regex_match(line, rx) ) {
// Input is number
n = std::stoi( line );
std::cout << n << "\n";
break;
}
}
return 0;
}
I have been trying to only allow positive integer input into my program. But works it is getting past with the character input and negative integers, decimal numbers. Any ideas how to fix that?
#include <iostream>
using namespace std;
int main()
{
int row, col, i, i1, j, test;
double n;
test = 0;
while (test == 0)
{
cout << "Enter the number of rows: " << endl;
cin >> row;
if (cin.fail() || row <= 0 || !(row == (int)row))
{
cout << "\nEntered value is wrong!";
printf("\n");
cin.clear();
cin.ignore();
test = 0;
}
else { test = 1; }
}
}
I have been trying to only allow positive integer input into my
program.
You can easily check it with the help of std::isdigit, if you take the user input as a string instead of an integer.
take the user input as a string.
for each character in the string, check whether it is a digit (using std::isdigit).
if any of the char's in the user input(which is a string) is not a valid digit, return the boolean = false.
if its true for all chars, the input is an integer and you can convert it back to integer using std::to_string.
Following is a sample code:
SEE LIVE
#include <iostream>
#include <cctype> // std::isdigit
#include <string>
#include <vector>
bool isInteger(const std::string& input)
{
for (const char eachChar : input)
if (!std::isdigit(eachChar))
return false; // if not a digit, return False
return true;
}
int main()
{
std::vector<std::string> inputs{ "123", "-54", "8.5", "45w" }; // some inputs as strings
for(const std::string& input: inputs)
{
if (isInteger(input))
{
// apply std::stoi(input) to convert string input to integer
std::cout << "Input is a valid integer: " << input << std::endl;
}
else { std::cout << input << " is not a valid integer!\n"; }
}
}
output:
Input is a valid integer: 123
-54 is not a valid integer!
8.5 is not a valid integer!
45w is not a valid integer!
This is what you probably want (demo):
#include <iostream>
#include <limits>
int main()
{
using namespace std;
int n;
while ( !( cin >> n ) || n < 0 )
{
cin.clear();
cin.ignore( numeric_limits<std::streamsize>::max(), '\n' );
}
//...
return 0;
}
As Mehdi Algholipour wrote i wanted to
1.Get string from input
2.Separate input to Integer numbers
3.Save them into Array
cout << "Give me some integers separated with space";
cin >> string; // example input 10 210 300 510
//..some code that seperate input to integer numbers and save them to Array
//EXPECTED RESULT: Array[0]=10 Array[1]=210 etc...
I think your mean is:
Get string from input
Separate input to Integer numbers
Save them into Array
If this is your mean, try this code:
string str;
int arr[1000]; // I supposed 1000 is your Int Array size.
int number = 0, index = 0;
getline(cin, str); // Get a line of string
for (int i = 0 ; i < str.length() ; i++){ // Processing your str Array
if (isdigit(str[i])){
number *= 10;
number += ((int)str[i] - '0');
}
else {
arr[index++] = number;
number = 0;
}
}
arr[index] = number; // for last element of your input
// Do something you want
Try:
#include <iostream>
#include <string>
#include <vector>
#include <regex>
int main()
{
std::regex rgx("\\b\\d+\\b");
std::string line;
std::cout << "Please enter numbers separated by spaces and press enter:" << std::endl;
std::getline(std::cin, line);
std::sregex_iterator it(line.begin(), line.end(), rgx);
std::sregex_iterator end;
std::vector<int> values;
std::transform(it, end, std::back_inserter(values), [](std::smatch s){ return std::stoi(s.str()); });
for (int v : values)
std::cout << v << std::endl;
}
Use stringstream:
string str;
getline(cin, str);
stringstream ss(str);
vector<int> vec;
int Integer;
while(true)
{
ss >> Integer;
if(!ss)
break;
vec.push_back(Integer);
}
live demo
Note: You need to include following headers: <string>, <sstream>, <vector>