首页 > 解决方案 > 如何将 SINGLE char 转换为系统字符串 C++?

问题描述

我正在开发一个在控制台应用程序中显示以下字符/整数的程序。
我编写的代码在控制台应用程序中工作,但在表单中不起作用......
我还想在我的表单中显示这些值(文本框->文本)。

我的 myfunctions.h 文件:


    typedef struct{
    
        char Header         [23]; //the char I want to display is 23 characters long
        int  Version        [4];  //4 characters...
        char Projectname    [21];
        char Developer      [8];
        char email          [16];
        char Description    [132];
        char Unknown        [1]; 
    
    }PackedContent;
    
    void BinaryReader(){
    
    system("CLS");
    
    PackedContent t;
    
    fstream myFile;
    
    myFile.open("PackedContent.opf");
    
    if(!myFile){
    
    
        cout<<"An unknown error occured! Cannot read .opf file... exiting now... \n"<<endl;
        
    
    }else{
    
        cout    <<"Reading packed data content... done!\n"<<endl;
        
        myFile.read((char *)&t, sizeof(PackedContent));
    
    
        cout<<"\nHeader      :"         <<t.Header              <<endl; //  Header info [ok]
        
        //cout<<"\nVersion     :"           <<t.Version             <<endl; //  Project Version [err]
        
        cout<<"\nProject name:"         <<t.Projectname             <<endl; //  Project name
        
        cout<<"\nDeveloper name:"       <<t.Developer<<endl;
        cout<<"\nEmail       :"         <<t.email               <<endl; //  Developer email
        cout<<"\nDescription :"         <<t.Description         <<endl; //  Project description [ok]
        cout<<"Unknown"                 <<t.Unknown             <<endl;
    }

形式:

Binary Reader.H (form)
PackedContent t;

BinaryReader();
textBox1->Text = t.Header; // doesnt work...

我也试过:
textBox1->Text = Convert::ToString(t.Header); //doesn't work...

标签: c++stringchar

解决方案


如果您的 char 数组是空终止的,例如 C 字符串,您可以将它按原样传递给 std::string c'tor:

textBox1->Text = std::string(t.Header)

您的 char 数组不是以 null 结尾的,因此您还应该提供大小,如下所示:

int headerSize = 1; // This variable is just for the example. Instead you can pass the size right in the function below

textBox1->Text = std::string(t.Header, headerSize)

或者:

textBox1->Text = std::string(t.Header, std::size(t.Header))

推荐阅读