【问题标题】:The output is always the same even if the algorithm works C/C++即使算法工作 C/C++,输出也总是相同的
【发布时间】:2020-07-23 08:18:51
【问题描述】:

我有这个 sn-p 代码检查格式化文件中最大的数字集,即使算法有效,获取所述值的位置,输出始终是最后读取的行。发生了什么?

int main() {
int n, north_key, east_key;
char *identity, *time, *eastIdentity, *eastTime, *northIdentity, *northTime;
float latitude, longitude, max_east = MIN, max_north = MIN;
input = fopen("level2-1.in", "r");
fscanf(input, "%d", &n);
for(int i = 0; i <= n; i++) {
    char line[MAX];
    fgets(line, MAX, input);  
    identity = strtok(line, ","); 
    time = strtok(NULL, ",");

    char *aux = strtok(NULL, ",");
    latitude = std::atof(aux);
    aux = strtok(NULL, "\n");
    longitude = std::atof(aux);

    if(max_north < latitude) {
        max_north     = latitude;
        north_key     = i;
        northIdentity = identity;
        northTime     = time;
     }

    if(max_east < longitude) {
        max_east      = longitude;
        east_key      = i;
        eastIdentity  = identity;
        eastTime      = time;
    }
    printf("%d, %d\n", north_key, east_key);
}
printf("%s,%s, %s,%s\n", northIdentity, northTime, eastIdentity, eastTime);
fclose(input);
return 0;

}

【问题讨论】:

  • 在调试器中运行你的程序。
  • 这是 C 而不是 C++。哦,等等,没有那个 std::atof 使它成为 C++。
  • 如果没有得到预期的输出,算法怎么会起作用?
  • @user4581301 好吧,north_key 和 east_key 变量实际上 100% 正确。唯一的问题是打印的字符串总是从文件中读取的最后一行

标签: c++ c string


【解决方案1】:

输出都是指向line 段的指针,line 被每次迭代覆盖。此外,在打印输出时,line 已超出范围。访问无效内存会导致Undefined Behaviour

必须通过将输出复制到自己的存储来保存输出。

强烈考虑使用std::strings(并且可能一直使用strings 并用std::istringstream 代替strtok)。

注意事项:

for(int i = 0; i <= n; i++)

看起来它可能会读到最后一个。 i &lt;= n 允许 i 达到 n(范围为 [0, n])总共 n+1 迭代。你可能想要i &lt; n

【讨论】:

  • 由于 OP 将他的问题标记为“c++”而不是“c”,因此回答者建议使用 std::string 是合适的。但是,我怀疑 OP 可能正在寻找 C 风格的解决方案。如果是这种情况,那么他应该将标签更改为“c”。
  • 是否有任何方法可以存储所需的字符串,即使它们不断变化?另外,我知道 i to n 问题,我用这种方式快速解决了程序没有从文件中读取我的最后一行的事实。它绝不是完美的,但它确实可以帮助我调试程序
  • @Bozgorian 为输出变量分配存储空间。当您找到新的最大值时,将当前值写入该存储。使用std::string 就像馅饼一样简单。如果不能使用std::string,请使用数组和strcpy
猜你喜欢
  • 2010-09-12
  • 2015-08-09
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多