C++ 奇怪的循环

标签 c++ loops

我写了这个函数。调试时,我看到在函数的最后,它转到 string cmonth[] declare 然后回到函数的最后,然后回到 string cmonth[ ] 声明,大约10次。然后它返回到函数的第一行,然后返回到函数的最后一行大约 100 次或更多次。

int CheckLastDate(string file)
{
string line, dline[200];
int i = 0;
regex rxdate("[[:digit:]].:[[:digit:]].:[[:digit:]].");
ifstream infile;
infile.open(file.c_str());

if(! infile.is_open()) return -1;

while (infile.good())
{
    getline(infile, line);
    if(regex_search(line, rxdate))
    {
        dline[i] = line;
        i++;
    }
}
i--; //needed b/c dline starts at 0;
infile.close();

int imonth, day, hour, min, sec, year;
string month, ampm;
string cmonth[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

month = dline[i].substr(5,3);
//convert month to number
for(int j = 0; j<12; j++)
{
    if(month == cmonth[j]) imonth=j+1;
}

day = atoi(dline[i].substr(9, 2).c_str());
hour = atoi(dline[i].substr(12, 2).c_str());
min = atoi(dline[i].substr(15, 2).c_str());
sec = atoi(dline[i].substr(18, 2).c_str());
ampm = dline[i].substr(21, 2);
year = atoi(dline[i].substr(24, 4).c_str());

if(ampm == "PM" && hour != 12) { hour += 12; } //turn into 24 hours
else if(ampm == "AM" && hour == 12) { hour = 0; }

time_t now, dif; //dif = date in file
double diff;
time(&now);
struct tm * timeinfo;
timeinfo = localtime(&now);
timeinfo->tm_mon = imonth - 1;
timeinfo->tm_mday = day;
timeinfo->tm_hour = hour;
timeinfo->tm_min = min;
timeinfo->tm_sec = sec;
timeinfo->tm_year = year - 1900;
timeinfo->tm_isdst = -1; //-1 = no info
dif = mktime(timeinfo);
diff = difftime(now, dif);

if(diff >= 86400) return 1; //more then 24 hours
else return 0;
}

有什么问题吗,还是 C++ 的工作原理? 感谢您的帮助。

最佳答案

看起来不错,但有一些一般性的建议:

即使找到月份,您的 for 循环检查月份也会遍历所有月份, 这似乎是不必要的。

你应该养成总是初始化所有变量的习惯。在 Debug模式下,变量可能会被初始化,但在 Release模式下,它们通常不会。

您应该添加一些检查以确保正则表达式返回的字符串具有您期望的格式。例如检查长度。您也可以使用 strtok_s()如果标记用空格分隔,则将字符串分开。 token 始终具有特定长度或位于特定索引可能比预期更安全。

当您从文件中读入时,如果文件超过 200 行,则不会进行检查以防止出错。你应该考虑这个。例如while (infile.good() && i < 200)

关于C++ 奇怪的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11772035/

相关文章:

Python:如何根据位置输出FASTA头或染色体索引图?

python - 您可以将一个 for 循环嵌套在另一个 for 循环中,并且它们具有相同的循环变量吗?

C++ - 局部未初始化变量的值

c++ - 使用奇数流中的模生成 'random' 数字

python - 为什么我的 "if"语句在使用 "break"函数时没有退出?

python - 并行独立进程

algorithm - 打印二维图案

c++ - Boost spirit x3 解析器不适用于多个属性

c++ - 指向成员的指针对于托管类无效

C++ "hello world"Boost tee 示例程序