0
我有一个QTableWidget,其中用户输入各种样式的复杂数字。 例如,复数(-15 + 8.14i)可以写成像:如何从用户输入中获取数据?
-15 + 8.14i
-15 + 8.14j
-15 + J 8,14
-15+ i8,14
我也可以Ĵ! 这两个值都可能很大(它们被保存为双倍),也是负值。它们可以用“,”和“”来书写。 (所以3.14和3,14是相等的)。当用户错误地输入号码时应该有错误信息。
CKomplex fromString(QString str) { // ckomplex is my custom class for complex numbers
double numReal, numImag;
QString strNew = "";
// delete all spaces
for (int i= 0; i< str.length(); i++) {
if (!str[i].isSpace()) {
strNew += str[i];
}
}
QString part1 = "";
int index;
// get the first number
for (int i= 0; i < strNew.length(); i++) { // iterate string
if (strNew[i] != '+' && strNew[i] != '-') {
part1 += strNew[i];
} else { // e.g.: 5 + 3j -> the loop is at the "+"
if (i != 0) {
index = i; // save index at "+" to start for next number
break;
}
}
}
numReal = part1.toDouble();
QString part2 = "";
// get the second number
for (int i= index; i < strNew.length(); i++) {
if (strNew[i].isDigit() || strNew[i] == '+' || strNew[i] == '-' || strNew[i] == '.' || strNew[i] == ',') { // ignore j or i
part2 += strNew[i];
}
}
numImag = part2.toDouble();
return CKomplex(numReal, numImag);
}
这对基本输入无效。但不是很快,不可读或不实用。它只包含几个输入的可能性(像“-3-5,14”这样的东西不起作用)。有没有更简单的方法来将字符串转换为复数,而没有太多的循环和变量?
感谢您的代码, –
**什么的std :: istringstream ISS(STR) ;做? (sry for double post) –
YVW它从'std :: string'创建一个'std :: istringstream',然后使用regex迭代器进行迭代。 – wally