How to read in values in C++ without a space? [duplicate] - c++

Yes, this is for an assignment. I do not mind working to get an answer and I do not want the exact answer! :) This is my first C++ class. I've come into this class with prior knowledge of VBA, MySql, CSS, and HTML.
We are required to write a program with several different functions. One of them is required to receive the date input in a "MM/DD/YYYY" format.
While that in of itself is easy enough; as a beginner I would just put
cin >> month >> day >> year;
And insert the "/" afterwards when displaying back to the user.
However, I believe our professor would like the user to input the date by exactly typing "12/5/2013", or any other date.
Per his instructions:
The '/' can be read by cin. So read the '/' character and ignore it. Set day to equal the 3rd input, month to the first input, and year to the fifth input. Discard the 2nd and 4th input.
^ That is where I am thrown off course.
So far we have only experienced cin when the user hits enter after each input. So I don't know if he wants the user to hit enter after 12, then again after '/', then after 5, after '/', and lastly after '2013' (using the prior example of 12/5/2013 for December 5th, 2013).
Does anyone more experienced have any possible insight as to what I should be doing?
We have only been taught how to use "cin" to receive inputs (so we know no other methods for receiving input), and I have no idea how to go about "ignoring a character" when entered as a string such as '12/5/2013' exactly.
I would greatly appreciate any help with this!
edit: I have looked for answers on here but all of the ones that I have come across are beyond the scope of what we have been taught and are therefore not allowed in the assignment.
While I can go about understanding the logic of more advance coding easily enough, I am frustrated at my lack of ability to solve these simpler problems with any amount of ease. Hence my posting on here. I have spent several hours scanning our textbook for possible answers or clues to 'ignoring' characters in an input string but have come up short.

It's actually pretty easy! The thing is: you can input more than just one thing. That means, if you write int d; std::cin >> d;, it's perfectly fine to input 30/06/2014. The value of d becomes 30 and the rest of the input is not yet read. If you write the next std::cin statement, the content that is available is /06/2014.
You then need to consume the /, read the month, consume again and finally read the year.
#include <iostream>
int main()
{
int d;
int m;
int y;
std::cin >> d; // read the day
if ( std::cin.get() != '/' ) // make sure there is a slash between DD and MM
{
std::cout << "expected /\n";
return 1;
}
std::cin >> m; // read the month
if ( std::cin.get() != '/' ) // make sure there is a slash between MM and YYYY
{
std::cout << "expected /\n";
return 1;
}
std::cin >> y; // read the year
std::cout << "input date: " << d << "/" << m << "/" << y << "\n";
}
If you have the guarantee that the input format will be correct, it's OK to just write
std::cin >> d;
std::cin.get();
std::cin >> m;
std::cin.get();
std::cin >> y;
Alternatively, If you're not comfortable with using std::cin.get(), it's just as good as reading a character:
char slash_dummy;
int d;
int m;
int y;
std::cin >> d >> slash_dummy >> m >> slash_dummy >> y;
Here are some demos:
code with error checks
ignoring errors
without std::cin.get()

follow this pseudo code:
declare a char pointer to accept input
declare int to use as day, month and year
initialize day, month and year to 0
declare a int count to know what number you are up to
read `cin` operation into your input
increment through the input, stop if the current input position is NULL
read out character
if character != "/"
if count == 0
if month == 0
month = (int)character
else
month = month * 10 + (int)character
endif
else
if count == 1
if day == 0
day = (int)character
else
day = day * 10 + (int)character
endif
else
if year < 1000
year = year * 10 + (int)character
endif
endif
endif
else count += 1 endif
and voilĂ  you have your day, month and year from input.

Why not use stringstreams?
string input;
int year, month, day;
cin >> input; // input can be 2005:03:09 or 2005/04/02 or whatever
stringstream ss(input);
char ch;
ss >> year >> ch >> month >> ch >> day;

Related

How to not accept a float when inputting an int in c++

I am currently trying to write a program at school involving a random number generator for rolling a dice. I have written the code successfully, but I am trying to improve it so that the size of the dice and the number the user is trying to roll can be chosen by the user.
I have written code that does this, and I have also added code that repeats the request for input if the wrong value (ie not one of the dice sizes offered or trying to roll a number outside the range of the dice) or input type (ie var instead of int) is entered. However, if a floating point number is entered, and the number to the left of the floating point is in the correct range of values, it is using that number.
For example:
int size = 0;
cout << "Please choose the size of the dice to roll (6, 12 or 20): ";
cin >> size;
while (size != 6 && size != 12 && size != 20 || !cin)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid number entered. Choose the size of the dice to roll (6, 12 or 20): ";
cin >> size;
}
This will correctly ask to repeat the input if any letters or any numbers that aren't 6, 12 or 20 are entered, but if 20.125 (or any floating point number that is 6.- 12.- or 20.-) is entered it will take the number and move on to the next bit of code. This also happens if I enter a valid number followed by letters (ie 6f).
I tried modifying the condition of the while loop to:
while (size != 6 && size != 12 && size != 20 || !(cin >> size))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid number entered. Choose the size of the dice to roll (6, 12 or 20): ";
cin >> size;
}
And that fixes the problem, and it asks me for another input if I enter 12.5 or 20R etc, but then when I enter a correct input (6, 12 or 20) it just takes me to a new line in the debugger without moving to the next line of code. If I then enter a correct input again, it reads it at takes me to the next line of code.
I don't quite understand why one works 99% how I want it to with one error, and the other fixes that error but then gives me another one.
Thanks in advance, any advice guidance is much appreciated!
The way cin >> some_int_variable will interpret the input is character by character, until it stops making sense as an int. For instance, when it encounters . or f, cin is done reading that int.
If you want a different behavior, you will have to implement it yourself. Specifically, how do you stop processing one input, and starts processing the next?
cin >> some_int_variable will stop when it is no longer a valid it, cin >> some_std_string_variable will stop when it encounters an white-space character (new lines included). How about your problem? How do you want to separate one input from the next?
If white-space is a sensible approach, you can do so:
std::string word;
std::cin >> word;
int value;
bool error = false;
try {
size_t pos;
value = std::stoi(word, &pos);
// Was the full string used to build the int?
if(pos != word.size()) error = true;
} catch(std::logic_error&) {
error = true;
}
if(error) { /* something went wrong */ }
See the docs for std::stoi().
You could read a float, assign it to an integer variable and then compare the two. Something along these lines:
int integerSize;
float floatSize;
cin >> floatSize;
integerSize = floatSize; //Your program will perform a cast from float to integer, it will essentially truncate whatever appears after the floating point.
if (integerSize != floatSize) //Your program will now perform a cast from integer to float in order to compare the two, but if floatSize was not a whole number, this comparison should return false.
{
//code to ask for another value
}
That being said, floats (and doubles and long doubles) do experience rounding errors, so as another user suggested, the safest bet is to read a string and parse it yourself, or using a built-in function like std::stoi() (only for integers) and std::stof() (for floats).
template<typename T>
T typed_read_line(const std::string& prompt)
{
T result{};
std::string l;
std::cout << prompt << ":";
while (std::getline(std::cin, l)) {
std::istringstream line{l};
line >> result >> std::ws;
if (line.eof()) break;
//line contains more then expected
std::cout << "Again: " << prompt << ":";
}
return result;
}
https://godbolt.org/z/dfYKe3
Or version with extra validation or v3.

How to take input on same line in c++?

i want to input Date in this format 2/11/2015. how can i do this using
C++ ? Thanks The following method isn't working.
cin>>day >>month >>year ;
and also user don't have to press enter .
my Code is
#include <iostream>
using namespace std;
class Date
{
private :
int day,month,year;
char slash;
public :
void inputdate(void)
{
cout<<"Enter Date in Formate (day/month/year)"<<endl;
cin >> day >> slash >> month >> slash >> year;
}
void checkdate(void)
{
if (day<=0 || day>=32)
{
cout<<"Day is Wrong ! "<<endl;
}
if (month==2 && day>=29)
{
cout<<"February can have max 28 days !"<<endl;
}
if (month<=0 || month>=13)
{
cout<<"Month is wrong !"<<endl;
}
if (year<=1799 || year>=3000)
{
cout<<"Year is Wrong !"<<endl;
}
if ((month==4 || month==6 || month==9 || month==11)&&(day>30))
{
cout<<"Day is wrong ! September ,April ,June and November can have maximum 30 days ."<<endl;
}
}
void showdate(void)
{
checkdate();
cout<<"Date is : "<<day<<"/"<<month<<"/"<<year<<endl;
}
};
C++ does not inherently understand text dates; you will need to either use a library which provides this functionality, or create a function yourself to convert between the text format and the internal integer format (which is generally the number of seconds or milliseconds, depending on platform, since the "Epoch" (00:00 1st January 1970)).
To do this you will need to:
Collect the date as a single string or character array
Separate the date into its constituent day/month/year
Calculate this date as a number of seconds since the Epoch
Having said all this, the first option of using a Library is probably best as it will also contain functions to switch between string and internal date format; which library you choose is up to you and will largely depend on the platform you're coding for.
You can use a dummy char variable to read past the / separator:
int day, month, year;
char slash; // dummy to skip past the '/'
cin >> day >> slash >> month >> slash >> year;

Trying to split a string into two integers [duplicate]

This question already has answers here:
How to read n integers from standard input in C++?
(7 answers)
Closed 7 years ago.
So I want to split a string (entered to the console) into two integers.
The first integer will always be one digit at position 0 in the string. Then, there will be a space. Everything after that space will be the second digit.
Here is my code:
struct priority_element
{
int id;
int priority;
} priorityQueue[1000];
string input;
cin << input;
priority_element temp;
string priority = input.substr(0, 1);
string id = input.substr(1, input.size());
temp.priority = atoi(priority.c_str());
temp.id = atoi(id.c_str());
priorityQueue[0] = temp;
cout << priorityQueue[0].priority;
cout << priorityQueue[0].id;
I included the priority_element struct so you could see what it was.
I keep trying to enter a string, something like:
5 6
or
5 5000
I can print the priority (5), but printing the priority and id together like in my example code has the output of 50.
If I try to print the id alone then the output is empty.
Could anyone understand why this is happening?
Thanks!
std::cin will stop passing at spaces, so you should read the whole line to input by using
// cin >> input;
std::getline(cin, input);
As suggested by others, actually, this can be done simply by:
std::cin >> temp.priority >> temp.id;
The streams in C++ are made for just this type of thing.
(from iostream)
int x,y;
std::cin >> x;
std::cin >> y;
std::cout << x << y << std::endl;
string id = input.substr(1, input.size());
here you got a space not the second digit
English is not my first langage , hope you can understand

How to get input from cin, which are seperated by colon?

I am trying to get time input like 12:30:00 which is hour:minute:second and then put them in a struct. Im using cin but it only works when i use space instead of colon like 12 30 00. How can i make it work with colon instead of space? Please be as easy as possible im very newbie about this.
An example could be like:
struct time{
int hour,minute,second;
long acc_seconds;
}tm;
int main(){
cout <<"Please enter date as HH:MM:SS";
cin >> tm.hour>>tm.minute>>tm.second;
}
Use a place holder object to read the ':' into. Read the numbers into the right objects.
char dummy;
cout << "Please enter date as HH:MM:SS";
cin >> tm.hour >> dummy >> tm.minute >> dummy >> tm.second;
Sometimes the old is better
scanf("%d:%d:%d", &tm.hour, &tm.minute, &tm.second);
you can store time in String and then divide it into hr,min,sec based on position of 2 colon and then store it in 3 integers.

Prompt for and receive a date "MM/DD/YYYY" using CIN, ignoring the "/" characters? (in C++)

Yes, this is for an assignment. I do not mind working to get an answer and I do not want the exact answer! :) This is my first C++ class. I've come into this class with prior knowledge of VBA, MySql, CSS, and HTML.
We are required to write a program with several different functions. One of them is required to receive the date input in a "MM/DD/YYYY" format.
While that in of itself is easy enough; as a beginner I would just put
cin >> month >> day >> year;
And insert the "/" afterwards when displaying back to the user.
However, I believe our professor would like the user to input the date by exactly typing "12/5/2013", or any other date.
Per his instructions:
The '/' can be read by cin. So read the '/' character and ignore it. Set day to equal the 3rd input, month to the first input, and year to the fifth input. Discard the 2nd and 4th input.
^ That is where I am thrown off course.
So far we have only experienced cin when the user hits enter after each input. So I don't know if he wants the user to hit enter after 12, then again after '/', then after 5, after '/', and lastly after '2013' (using the prior example of 12/5/2013 for December 5th, 2013).
Does anyone more experienced have any possible insight as to what I should be doing?
We have only been taught how to use "cin" to receive inputs (so we know no other methods for receiving input), and I have no idea how to go about "ignoring a character" when entered as a string such as '12/5/2013' exactly.
I would greatly appreciate any help with this!
edit: I have looked for answers on here but all of the ones that I have come across are beyond the scope of what we have been taught and are therefore not allowed in the assignment.
While I can go about understanding the logic of more advance coding easily enough, I am frustrated at my lack of ability to solve these simpler problems with any amount of ease. Hence my posting on here. I have spent several hours scanning our textbook for possible answers or clues to 'ignoring' characters in an input string but have come up short.
It's actually pretty easy! The thing is: you can input more than just one thing. That means, if you write int d; std::cin >> d;, it's perfectly fine to input 30/06/2014. The value of d becomes 30 and the rest of the input is not yet read. If you write the next std::cin statement, the content that is available is /06/2014.
You then need to consume the /, read the month, consume again and finally read the year.
#include <iostream>
int main()
{
int d;
int m;
int y;
std::cin >> d; // read the day
if ( std::cin.get() != '/' ) // make sure there is a slash between DD and MM
{
std::cout << "expected /\n";
return 1;
}
std::cin >> m; // read the month
if ( std::cin.get() != '/' ) // make sure there is a slash between MM and YYYY
{
std::cout << "expected /\n";
return 1;
}
std::cin >> y; // read the year
std::cout << "input date: " << d << "/" << m << "/" << y << "\n";
}
If you have the guarantee that the input format will be correct, it's OK to just write
std::cin >> d;
std::cin.get();
std::cin >> m;
std::cin.get();
std::cin >> y;
Alternatively, If you're not comfortable with using std::cin.get(), it's just as good as reading a character:
char slash_dummy;
int d;
int m;
int y;
std::cin >> d >> slash_dummy >> m >> slash_dummy >> y;
Here are some demos:
code with error checks
ignoring errors
without std::cin.get()
follow this pseudo code:
declare a char pointer to accept input
declare int to use as day, month and year
initialize day, month and year to 0
declare a int count to know what number you are up to
read `cin` operation into your input
increment through the input, stop if the current input position is NULL
read out character
if character != "/"
if count == 0
if month == 0
month = (int)character
else
month = month * 10 + (int)character
endif
else
if count == 1
if day == 0
day = (int)character
else
day = day * 10 + (int)character
endif
else
if year < 1000
year = year * 10 + (int)character
endif
endif
endif
else count += 1 endif
and voilĂ  you have your day, month and year from input.
Why not use stringstreams?
string input;
int year, month, day;
cin >> input; // input can be 2005:03:09 or 2005/04/02 or whatever
stringstream ss(input);
char ch;
ss >> year >> ch >> month >> ch >> day;