简体   繁体   English

CString在MFC中编辑控件

[英]CString to Edit Control in MFC

So i'm retrieving so data from a .txt file to a myclass (class), including 所以我正在将数据从.txt文件检索到myclass(类),包括

public:
vector<int> ID
vector<string> name
vector<string> add

but when i try to access them to show them in an edit box in a MFC dlg it just returns me this to the box: 但是,当我尝试访问它们以在MFC dlg的编辑框中显示它们时,它将返回此框:

ID: 1
Name: (jibberish)
address: (jiberish)
ID: 2
Name: (jibberish)
address: (jiberish)
etc...

code used in the edit control box in a for cycle for循环中的编辑控制框中使用的代码

int s1;    
CString s2, s3;
s1.Format(_T("\r\nID: %d"),myclass.ID[i]);
s2.Format(_T("\r\nName: %s"),myclass.name[i]);
s3.Format(_T("\r\nAddress: %s"),myclass.add[i]);
Edi_box += s1 + s2 + s3;

so it reads the vector of integers but not the vector of strings 因此它读取整数的向量,但不读取字符串的向量

You cannot (or at least should not) format a std::string using %s . 您不能(或至少不应)使用%s格式化std::string Try this: 尝试这个:

s2.Format( _T("\r\nName: %s"), myclass.name[i].c_str() );

and proceed likewise for other std::string variables. 并对其他std::string变量同样进行。

The _T macro will create a wchar_t string or a char string, depending on the charset settings of the VS project. _T宏将创建一个wchar_t字符串或一个char字符串,具体取决于VS项目的字符集设置。 In order to format a std::string (which is char-based) into one of those, you have to use the right conversion. 为了将std::string (基于字符)格式化为其中之一,您必须使用正确的转换。 Microsoft ships an extension to the "normal" printf() -style syntax that is supported by many functions: Use the %ls to insert a wchar_t string and %hs for a char string. Microsoft提供了对“正常” printf()样式语法的扩展,该扩展受许多功能支持:使用%ls插入wchar_t字符串,并使用%hs插入char字符串。

Notes: 笔记:

  • The conversion from wchar_t to char can fail, so don't expect quality results there unless you have a restricted input already. 从wchar_t到char的转换可能会失败,因此除非那里的输入已经受限,否则不要期望在那里得到高质量的结果。
  • You can't pass any class-type objects through an ellipsis, so you need the C-style, NUL-terminated string from the c_str() function. 您不能通过省略号传递任何类类型的对象,因此您需要c_str()函数的C样式,NUL终止的字符串。
  • If you have multiple vectors where each element corresponds to one element of the other, use a single vector with a struct, it makes your code much clearer. 如果您有多个向量,其中每个元素对应于另一个元素,请使用带有结构的单个向量,这样可使您的代码更加清晰。
  • Put the end-of-line characters ("\\r\\n") at the end . 将行尾字符(“ \\ r \\ n”)放在末尾 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM