C ++中的CString.Append() [英] CString.Append() in C++

查看:208
本文介绍了C ++中的CString.Append()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在返回字符串的简单函数中遇到问题:

I have problems in a simple function that returns a string:

if (format == style1)
    (value >= 0) ? str.Append(_T(">")) : str.Append(_T("<"));



我想包括另一个if条件,但不附加任何symbol.ie;



I want to include another if condition without appending any symbols.ie;

if (format == style2)
 (value >= 0) ? str.Append(_T(" ")) : str.Append(_T(" ")); 



但这是行不通的.还有其他方法吗?


作为MFC类的CString添加了MFC标签.



But this does not work. Is there any other way to do this?


Added MFC tag as CString''s an MFC class.

推荐答案

每个分支看起来像它使用CString :: Append为什么不通过执行以下操作来简化代码:

As every branch looks like it uses CString::Append why not simplify your code by doing something like:

if (format == style1) str.Append( (value >= 0 ) ? "<" : ">" ); 


甚至走有条件的免费路线并使用查找表:


Or even go the conditional free route and use a lookup table:

const *char appendable_strings[][] = { { "<", ">" }, { " ", " " } };

str.Append( appendable_strings[format][value < 0] );


并将格式和样式映射到基于0的整数.代码将更小,可能更快,更容易阅读.并将其粘贴在函数中,这样您就可以更好地了解当您不正确地执行操作时编译器在做什么.

干杯,



PS:不确定数组索引是否正确"-我不经常使用数组.

PPS:另一个技巧是忘记CString-std :: string和std :: ostringstream将执行您所有的格式化需求.

捕获的母语失败异常

编辑II,恐怖继续:按照查克的以下建议,加上条件,我错过了最初的海报,想为style2附加一个空格字符.


and map format and style onto 0 based integers. The code will be smaller, probably faster and a lot easier to read. And stick it in a function so you''ve got a better idea what the compiler is whinging about when you do something incorrectly.

Cheers,

Ash

PS: Not sure the array indices are ''round the right way - I don''t use arrays that often.

PPS: As another tip forget CString - std::string and std::ostringstream will perform all your formatting needs.

Caught Native Language Fail Exception

Edit II, the Horror Continues: Slung a conditional in as per Chuck''s suggestion below and the fact that I''d missed the original poster wanting a space character appended for style2.


这篇关于C ++中的CString.Append()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆