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.
Related
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;
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
I get an error when I try to run this. It lets me input the employee's name, and then once I press Enter it skips to the end, flying by hours and pay rate without letting me input them.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
string EmployeeName; //Employee Name
float EmployeeHours;
float EmployeePayRate; //Emplyee Hours, Employee PayRate
cout << setw(50) << "Employee Name: ";
cin >> EmployeeName;
cout << setw(50) << "EmployeeHours: ";
cin >> EmployeeHours;
cout << setw(50) << "EmployeePayRate: ";
cin >> EmployeePayRate;
system("PAUSE");
return 0;
}
I think the comment by #AleksandarStojadinovic provides the clue to your problem. Use
std::getline(std::cin, EmployeeName);
to read the name. Rest can be as they are.
I am having an error when I try to run this. It lets me input the
employees name, and then once you press enter it skips to the end.
flies by hours and pay rate without letting me input that.
Your name must be comprised of two/three names, maybe first middle and last or something like that. cin deals space separated string and enter separated string in the same way i.e it will take each space separated string as different input. And for that if your name has two names, the first one goes right but the second one goes to a variable which is declared as float and the program terminates abnormally. That's why using cin in this case isn't right at all.
You need to use another way to avoid that, like using getline(cin,EmployeeName) .
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;
I'w writing piece of code and I should read variables from for loop:
#include <iostream>
using namespace std;
#define NumOfStudents 100
#define NumOfCourses 15
struct Student{
int stdnum, FieldCode, age;
double average, res[NumOfCourses];
char name[20]; //First and Last name length
};
int main(){
struct Student students[NumOfStudents];
int i;
cout << "\tNAME || STUDENT-NUMBER || FIELD-CODE || AGE";
for(i=0; i<NumOfStudents; i++){
cout << "\nSTUDENT #" << i+1 << ": ";
cin >> students[i].name[20] >> students[i].stdnum >> students[i].FieldCode >> students[i].age;
// cin >> students[i].name[20];
}
}
EDIT:
output is:
./st
NAME || STUDENT-NUMBER || FIELD-CODE || AGE
STUDENT #1: test
STUDENT #2:
STUDENT #3:
STUDENT #4:
.
.
.
STUDENT #100:
I can just enter name of first student and loop doesn't work correctly
what is the problem?
cin >> students[i].name[20];
It shouldn't be an array of 20. It means your entered first character is stored in index 20th location which is in-correct and can cause undefined behavior as name array is indexed from 0 to 19 only.
Rather it should be cin >> students[i].name, which writes into base address of array name
I think you have to write
cin >> students[i].name
Since it is a 1D array, subscript should not be used in getting input.
cin >> students[i].name[20]
This part is wrong. This command reads one character from standard input and stores it in the 20th position in name (i.e. in the byte right after the array name). You want to use:
cin >> students[i].name >> ...
In line "cin >> students[i].name[20]".
You can't use name[20] as input variable for a character string as it points to a character at index 20, which also do not exists in your case as char name[20] stores in indexes 0-19.
Correct format:
cin>>students[i].name;
To read string of characters or name as a string.
First of all, you need to use students[i].name without the index. Your syntax tries to insert the single character it reads from the terminal beyond the end of the char array and thus messing with the pointer (note that you should make sure that the input is truncated anyway).
Second, you should type all input parameters for each student, you cannot just insert their name. So input would be:
$ ./st
STUDENT #1: TestName 3456 1 15
If that's not intended behaviour, you might want to do multiple cin >> variable statemates.
Can you make it more clear. Is it that you are not able to enter the details after the first name is typed in? Or is it that the loop is exited before the entire operation is performed?
In you code, there's a problem, I guess
students[i].name[20]
here only one character is read. This should be replaced in cin with
students[i].name
Also if you are not able to enter the details after the first iteration, try to give fflush() or setbuf() to clear the input buffer.
Also if you have to read a string with spaces, try to use cin.getline() or gets(). The format for these are available in the net.
Thank you