简体   繁体   中英

CString to Edit Control in MFC

So i'm retrieving so data from a .txt file to a myclass (class), including

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:

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

code used in the edit control box in a for cycle

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 . Try this:

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

and proceed likewise for other std::string variables.

The _T macro will create a wchar_t string or a char string, depending on the charset settings of the VS project. In order to format a std::string (which is char-based) into one of those, you have to use the right conversion. 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.

Notes:

  • The conversion from wchar_t to char can fail, so don't expect quality results there unless you have a restricted input already.
  • 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.
  • 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 . ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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