【发布时间】:2011-12-06 18:27:36
【问题描述】:
我希望以下代码从价格中删除前导零(应将 0.00 削减为 .00)
QString price1 = "0.00";
if( price1.at( 0 ) == "0" ) price1.remove( 0 );
这给了我以下错误:“错误:从‘const char [2]’到‘QChar’的转换不明确”
【问题讨论】:
我希望以下代码从价格中删除前导零(应将 0.00 削减为 .00)
QString price1 = "0.00";
if( price1.at( 0 ) == "0" ) price1.remove( 0 );
这给了我以下错误:“错误:从‘const char [2]’到‘QChar’的转换不明确”
【问题讨论】:
主要问题是 Qt 将 "0" 视为以 null 结尾的 ASCII 字符串,因此编译器消息是关于 const char[2]。
另外,QString::remove() 接受两个参数。所以你的代码应该是:
if( price1.at( 0 ) == '0' ) price1.remove( 0, 1 );
这在我的系统上构建和运行(Qt 4.7.3,VS2005)。
【讨论】:
试试这个:
price1.at( 0 ) == '0' ?
【讨论】:
问题在于'at'函数返回一个QChar,它是一个无法与原生字符/字符串“0”进行比较的对象。你有几个选择,但我这里只放两个:
if( price1.at(0).toAscii() == '0')
或
if( price1.at(0).digitValue() == 0)
digitValue 如果 char 不是数字,则返回 -1。
【讨论】:
price1.at(0).digitValue()。
QChar::QChar(char) 似乎是非显式的,所以...at(0) == '0' 也应该这样做。
QString s("foobar");
if (s[0]=="f") {
return;
}
【讨论】:
QChar QString::front() const 返回第一个字符 细绳。与 at(0) 相同。
提供此功能是为了兼容 STL。
警告:在空字符串上调用此函数构成 未定义的行为。
http://doc.qt.io/qt-5/qstring.html#front
QString s("foobar");
/* If string is not empty or null, check to see if the first character equals f */
if (!s.isEmpty() && s.front()=="f") {
return;
}
【讨论】: