Reputation: 147
My code allows the user to input numbers, it sorts them, and outputs them in order.
Example input: 25,1,3-6
Example output: 1,3,4,5,6,25
However when the user inputs something like 2 5,1,3-6
, and if there is a space in a case like 3 - 6
, the program doesn't work.
I used cin>>ws;
to try to get rid of whitespace, however it is not working.
Here is the part of the code related to this issue (there are a few other functions I did not include, unless they seem to the source of the issue):
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
void get_nums(vector<int>& num_vec);
int main ()
{
int num1;
int num2;
cout << "\n Please, enter your HW: ";
vector<int> num_vec;
cin>>ws;
cout.flush();
do
{
cin>>ws;
cin>>num1;
num_vec.push_back(num1);
if(cin.peek() == ',')
{
cin.ignore();
}
else if(cin.peek() == '-')
{
cin.ignore();
cin>>num2;
for(++num1; num1<=num2; num1++)
{
num_vec.push_back(num1);
}
if(cin.peek() == ',')
{
cin.ignore();
}
}
}
while (cin.peek() != '\n');
cout<< "\n Do Problems: ";
for(int z=0; z<num_vec.size(); z++)
{
if(z+1==num_vec.size())
{
cout<<num_vec[z];
}
else if(z+2==num_vec.size())
{
cout<<num_vec[z]<<",and ";
}
else
{
cout<<num_vec[z]<<", ";
}
}
return 0;
}
Upvotes: 0
Views: 148
Reputation: 596307
I would use std::getline()
to read the user's entire input in one go, and then use std::istringstream
to parse it, eg:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
void get_nums(std::vector<int> &num_vec)
{
std::string line, tokens;
std::getline(std::cin, line);
std::istringstream input(line);
while (std::getline(input, tokens, ','))
{
std::istringstream values(tokens);
int num;
if (!(values >> num))
continue;
values >> std::ws;
char ch = values.peek();
if (ch == '-')
{
values.ignore();
int num2;
if (!(values >> num2))
continue;
while (num <= num2)
num_vec.push_back(num++);
}
else if (ch == std::char_traits<char>::eof())
num_vec.push_back(num);
}
}
int main()
{
std::vector<int> num_vec;
std::cout << "\n Please, enter your HW: " << std::flush;
get_nums(num_vec);
if (!num_vec.empty())
{
std::sort(num_vec.begin(), num_vec.end());
std::cout << "\n Do Problems: ";
std::cout << num_vec[0];
for(int z = 1; z < num_vec.size(); ++z)
{
std::cout << ", ";
if ((z+1) == num_vec.size())
std::cout << "and ";
std::cout << num_vec[z];
}
}
else
std::cout << "\n No Input! ";
return 0;
}
Input: 25,1,3-6
Output: 1,3,4,5,6,25
Input: 25,1,3 - 6
Output: 1,3,4,5,6,25
Input: 2 5, 1 , 3- 6
Output: 1,3,4,5,6
1
1: 2 5
is not valid input in this code. If you want it to be, you will have to add some extra code to handle space-delimited numbers in addition to comma-delimited numbers.
Upvotes: 2