【问题标题】:Junk values in ofstream using strncpy使用 strncpy 在 ofstream 中的垃圾值
【发布时间】:2015-04-11 05:50:40
【问题描述】:

我正在运行以下程序。我在B.txt 中获取前63 个字符值,然后在A.txt 中附加浮点值,从A.txt 的第62 列开始,在B.txt 行的末尾

所以如果 B.txt 包含:

I am running the following program below. I am taking the firstXXXXXXXX

并且 A.txt 包含:

I am running the following program below. I am taking the fir3.14

我希望 B.txt 看起来像:

I am running the following program below. I am taking the first3.14

但是,我得到的输出是:

I am running the following program below. I am taking the firstBUNCH OF JUNK3.14

int main()
{
    loadfileB("B.txt");

    return 0;
}


void loadfileB(char* fileName)
{
    FILE* fp = fopen(fileName, "r");
    char line[82];
    vector<int> rownum;
    vector<float> temp;
    temp = loadfileA("A.txt");

    int i = 0;
    ofstream fout("output.txt");

    while (fgets(line, 81, fp) != 0)
    {
        radius=temp[i];
        char buffer[64]; 
        strncpy(buffer, line, 63);
        fout << buffer<< " " << radius << endl;
        i++;
    }
    fclose(fp);
}

vector<float> loadfileA(char* fileName)
{
    FILE* fp = fopen(fileName, "r");
    char line[82];
    vector<int> rownum;
    vector <float> tempvec;

    int i = 0;
    while (fgets(line, 81, fp) != 0)
    {
        float temp;
        getFloat(line, &temp, 60, 6);
        tempvec.push_back(temp);
    }
    fclose(fp);

    return tempvec;
}

void getFloat(char* line, float* d, int pos, int len)
{
    char buffer[80];
    *d = -1;
    strncpy(buffer, &line[pos], len);
    buffer[len] = '\0';
    sscanf(buffer, "%f", d);
}

【问题讨论】:

  • 你的第一个问题是你使用 C 函数和 C++ 的东西。

标签: c++ string char scanf strncpy


【解决方案1】:

strncpy 是一个不好用的函数。这是因为如果输入不适合缓冲区,它不会以空值终止其输出。您看到的垃圾是将非空终止缓冲区传递给期望空终止字符串的函数的结果。

最简单的解决方法是替换:

char buffer[64]; 
strncpy(buffer, line, 63);

与:

std::string buffer = line;
buffer.resize(63);

在您的其他用法中,您执行空终止,但是您永远不会检查len 是否小于80。同样,更简单的解决方法是:

std::string buffer( line + pos, len );
sscanf(buffer.c_str(), "%f", d);

getFloat 函数应该有某种方式发出错误信号(返回值;或者如果 sscanf 不返回 1 则抛出异常)。

当然,您也可以用 C++ 样式代码替换很多其他 C 样式代码,从而完全避免缓冲区大小问题。

【讨论】:

  • 我用 C++ 字符串方法替换了 C 方法。但是,现在我收到了一堆对我来说毫无意义的 missing ;missing } 错误
  • @user4352158 发送MCVE 并发布新问题
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
相关资源
最近更新 更多