【发布时间】:2017-05-18 19:35:26
【问题描述】:
我正在尝试从字符串中提取整数,例如用户输入可能是 5ft12in 或 5'12"`。
但是,当我的输入为 5ft1in 时,该代码有效,但在输入 5ft12in 时无效。
我想遍历整个字符串并提取3个数字,例如:
feet = 5
inches 1 =1
inches 2 = 2
但我似乎找不到问题。
我认为有一种方法可以将输入转换为stringstream,然后使用char 将整个字符串转换为peek,但我不太确定如何。
string feet = "";
string inches = "";
string inches2 = "";
for (int i = 0; i < height.size(); ++i) {
if (isdigit(height[i]) && (feet.empty())) {
feet = height[i];
} // end if
else if ((isdigit(height[i]) && (!feet.empty()))) {
inches = height[i];
}
else if ((isdigit(height[i]) && (!feet.empty() && (!inches.empty())))) {
inches2 = height[i];
} // end else if
}//end for
cout << "String of feet : " << feet << endl;
cout << "String of inches 1 : " << inches << endl;
cout << "String of inches 2 : " << inches2 << endl;
【问题讨论】:
-
std::istringstream应该这样做。 -
我真的是一个初学者,所以如果我把它放在一个 ss 中; istringstream iss1("5ft10in");我将如何提取 0? while (ch = iss1.peek()) { if (!isdigit(ch)) iss1.ignore();否则 { iss1 >> i; cout
-
找到“ft”和“in”的位置,查看它们之前和之间的子串。
-
我可以这样做,但用户也可以输入 5'12'' 所以必须遍历整个字符串并仅返回整数
-
看看
std::string的find_first_of()和find_first_not_of()方法。