设置字符串的宽度或将字符串添加到标签

时间:2014-12-03 17:57:44

标签: c++ string

我需要为窗体的标签设置字符串的宽度。在我搜索时,我没有找到任何字符串函数来设置宽度。我也尝试用ostringstream来做,但它似乎不起作用:(

            ostringstream oss;
            oos << "HI ";
            string str = oos.str();
            labek->Text += str;

1 个答案:

答案 0 :(得分:0)

看一下这个例子:

#include <iostream>
#include <sstream>
using namespace std;

int main(){
    wostringstream oss;
    oss.width(5); //<--- set desired width in characters
    oss.fill(' '); //<-- what fill character you want to use to complete to width. 
    oss << "HI ";
    wstring str = oss.str();
    //cout<<"'"<<str<<"'"<<endl;
    //now you should do: label->Text = str.c_str(); but, alas, I doesn't have this label...

    return 0;
}

修改

这对我有用。我在新表单中添加了名为label1的标签和一个名为button1的按钮。

当我按下按钮时,标签会被更改。

添加以下内容:

#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>

这是按钮点击功能:

   private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
        std::wostringstream oss;
        oss.width(15); //<--- set desired width in characters
        oss.fill('*'); //<-- what fill character you want to use to complete to width. 
        oss << "HI";
        std::wstring str = oss.str();
        label1->Text = msclr::interop::marshal_as<String^>(str);
    }