Before I ask anything, I should mention that I have a shaky foundation in C++. Let me know if I'm not being clear on anything and I will do my best to clarify.
My coding problem here is reading a series of 24-hour time values, with no seconds included, and storing them into an array of a structure. Reading the hours and minutes in integer format, and storing it into an array of structures is what I'm not understanding with this. In the text file, the first number in each row is the 24-hour time, and the second number is the amount of minutes that I need to modify the time with. I'm stuck frozen at just reading the times in to begin with.
This is the code I have so far.This is the result of the code.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int size = 7;
int i;
struct Times {
int T;
int M;
};
Times clock[7];
ifstream infile;
infile.open("times.txt");
for (i=0; i<size; i++){
infile>>clock[i].T>>clock[i].M;
}
for (i=0; i<size; i++){
cout<<clock[i].T << " "
<<clock[i].M <<endl;
}
}
Here is the contents of the text file:
6:45 39
12:00 73
0:00 4
23:59 1
22:45 70
11:59 1
14:15 95
Here is the updated code which seems to work:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int size = 7;
int i;
char colon;
struct Times {
int hour;
int minute;
int M;
};
Times clock[7];
ifstream infile;
infile.open("times.txt");
for (i=0; i<size; i++){
infile>>clock[i].hour>>colon>>clock[i].minute>>clock[i].M;
}
for (i=0; i<size; i++){
cout<<clock[i].hour << " "
<<colon << " "
<<clock[i].minute << " "
<<clock[i].M
<<endl;
}
}
Note that each line of your file contains three integral values, not two, and that a colon will stop reading in an integral value (formatted input for integrals will skip leading white spaces and even new line characters, but not "leading" colons). If you want to read an integral value that follows a colon, you'll need to skip the colon.
You could do this by reading in the colon into a variable of type char
(and ignoring it afterwards). The code could look as follows:
int main()
{
int hour,minute,x;
char colon;
stringstream s { "15:43 10\n16:48 20\n" };
while (s >> hour >> colon >> minute >> x) {
cout << "H:M=" << hour << ":" << minute << "; times=" << x << std::endl;
}
}
Output:
H:M=15:43; times=10
H:M=16:48; times=20