[英]Reading time entries from a text file and storing them into a 3D array so they are useable, in C++
我目前正在尝试将我拥有的程序从PHP转换为C ++并对其进行改进,但是我无法弄清楚如何读取数据以使其可用。
文本文件看起来像这样:
No. , user No., date, time
1 , 1, 2013-12-12, 08:00
2 , 2, 2013-12-12, 08:10
3 , 1, 2013-12-12, 12:00
4 , 2, 2013-12-12, 12:01
5 , 2, 2013-12-12, 12:55
6 , 1, 2013-12-12, 13:00
7 , 1, 2013-12-12, 17:00
8 , 2, 2013-12-12, 17:20
9 , 1, 2013-12-13, 08:00
10 , 2, 2013-12-13, 08:10
11 , 1, 2013-12-13, 12:00
12 , 2, 2013-12-13, 12:01
13 , 2, 2013-12-13, 12:55
14 , 1, 2013-12-13, 13:00
15 , 1, 2013-12-13, 17:00
16 , 2, 2013-12-13, 17:20
我的目标是阅读文本文件,并使用时间条目进行计算,确定当天的总工作时间,当天的加班时间以及当月的总时间和加班时间。
所以我的问题是如何阅读文本文件,所以我可以使用日期和时间条目。
编辑。 这是我的代码目前的样子。 我对C ++本身并不是很有经验,这就是为什么我正在用我更熟悉的语言重建我之前已经制作的程序。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int lines() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("data.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines << endl;
return number_of_lines;
}
int main ()
{
int Nr;
int name;
int year;
int month;
int day;
int hour;
int min;
int seconds;
int row = lines();
int myarray[16][8];
string line;
ifstream myfile ("data.txt");
if (myfile.is_open())
{
for(int i=0; i<row; i++){
getline (myfile,line);
sscanf(line.c_str(), "%i, %i, %i-%i-%i, %i:%i", &Nr, &name, &year, &month, &day, &hour, &min);
seconds=hour*60*60+min*60;
myarray[i][1] = Nr;
myarray[i][2] = name;
myarray[i][3] = year;
myarray[i][4] = month;
myarray[i][5] = day;
myarray[i][6] = hour;
myarray[i][7] = min;
myarray[i][8]=seconds;
}
myfile.close();
for(int i=0; i<16; i++){
for( int j=1; j<=8; j++){
cout << myarray[i][j] << " ";
}
cout << endl;
}}
else cout << "Unable to open file";
system("PAUSE");
return 0;
}
使用名为number,FirstName,LastName,Date和Time的字段创建结构或类。 逐行读取文件,并在每行上面创建一个结构或类的实例。 将所有这些实例放在您选择的容器中, std::vector
可能是最简单的。
然后编写一些循环遍历容器并计算你想要的任何东西。
如果你遇到这样的问题,请发布你最好的尝试和问题。
既然你已经发布了你的代码并且它不符合我建议的答案,我将尝试帮助解决实际的错误:
你的程序是C和C ++的混合体。 最好使用一种语言,无论是C语言还是C ++语言。
sscanf将const char *
作为第一个参数。 如果要从std :: string创建const char*
,请使用c_str()
函数:
sscanf(line.c_str(), "%d, %s, %s, %d-%d-%d, %d:%d", ...
接下来,您的程序将崩溃,因为您声明了您的名字和姓氏是整数。 因为情况并非如此,它将无法运作。 接下来修复你的声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.