【问题标题】:"incompatible types in assignment of 'char' to 'char'[100]" am I using strcat right?“将'char'分配给'char'[100]时的类型不兼容”我使用strcat对吗?
【发布时间】:2016-01-07 08:31:41
【问题描述】:

早安,

我正在为我的 IMU 编写一个数据记录程序。我想在记录每个值后添加一个换行符,但是,我不断在这一行收到错误:

strcat(file_DT,"\n");

错误指出“将'char'分配给'char'[100]时存在不兼容的类型”

我尝试过使用

file_DT+="\n"; 

早些时候,但事实证明它只适用于字符串。

我找不到任何解决方案来解决我的困境。有一个更好的方法吗?非常感谢您的帮助:)

float deltaTime2;
FILE *fileDT;
char file_DT[100];
const char *filenameDT = "dT.txt";

while(1){

    /* do quadcopter orentation sampling here */

// log DT
fileDT = fopen(filenameDT, "a+");
    if (fileDT){ //if file exists
        snprintf(file_DT, 100, "%f", deltaTime2);
        strcat(file_DT,"\n");
        fwrite(&file_DT[0], sizeof(char), 100, fileDT);
        cout << "Logging DT" << << endl;
        fclose(fileDT);
        fileDT = NULL;
    }
    else{ //no file, generate file
        cout << "No file present, generating new fileDT" <<     endl;
        snprintf(file_DT, 100, "%f", deltaTime2);
        strcat(file_DT,"\n");
        fwrite(&file_DT[0], sizeof(char), 100, fileDT);
        fclose(fileDT);
        fileDT = NULL;
    }

}

【问题讨论】:

  • 作为旁注,命名两个变量 file_DTfileDT 非常令人困惑。
  • 我怀疑您是否收到该行的错误(其中没有任何赋值提示)。与您的问题无关:您不需要strcat - 只需fwrite 在您编写file_DT 后换行即可。更好的是:使用std::ofstream fileDTfileDT &lt;&lt; deltaTime2 &lt;&lt; '\n';
  • 或者fprintf(file_DT, "%f\n", deltaTime2);,如果你决定写“C in C++”的话。
  • 在这里使用strcat 有什么意义?你也可以用"%f\n"而不是"%f"来调用snprintf。此外,您正在将一大堆零写入文件。为什么不使用fprintf 只写入实际数据?事实上,你也可以用fprintf 做所有事情,而不是snprintfstrcatfwrite 的奇怪组合。如果想利用 C++ 的好处,那么有适当的内置 (STL) 函数。
  • 1) “IMU”到底是什么意思? 2) strcat 不能正确使用,因为它在 C++ 中从来都不是合适的解决方案。

标签: c++ arrays char fwrite strcat


【解决方案1】:

可以改写以下几行

    snprintf(file_DT, 100, "%f", deltaTime2);
    strcat(file_DT,"\n");
    fwrite(&file_DT[0], sizeof(char), 100, fileDT);

作为

    int datalen = snprintf(file_DT, 100, "%f\n", deltaTime2);
    fwrite(&file_DT[0], sizeof(char), datalen, fileDT);

这样您就可以得到换行符并只写入所需的数据。 否则你最终会将垃圾写入文件(你的行可能短于 100 字节)

【讨论】:

  • “写垃圾”实际上是未定义的行为(将未初始化的变量传递给库函数),所以任何事情都可能发生
【解决方案2】:

如果我能建议这种代码最好用 C++ 编写

#include <iostream>
#include <fstream>
#include <string>
using namspace std;

const string filenameDT;

int main()
{
    ofstream file(filenameDT);
    file << deltaTime2 << endl;
    cout << "Logging DT" << endl;        
}

我们在 2016 年!不要那样写代码!

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多