【发布时间】:2017-04-18 03:19:35
【问题描述】:
很抱歉,我一直在寻找从这组字符串中提取整数的方法:
{(1,2),(1,5),(2,1),(2,3),(3,2),(3,4),(4,3),(4,5),(5,1),(5,4)}
我真的不需要做功课,如果你能给我一个例子,我会很感激的。 谢谢你。
【问题讨论】:
很抱歉,我一直在寻找从这组字符串中提取整数的方法:
{(1,2),(1,5),(2,1),(2,3),(3,2),(3,4),(4,3),(4,5),(5,1),(5,4)}
我真的不需要做功课,如果你能给我一个例子,我会很感激的。 谢谢你。
【问题讨论】:
如果您只想从这样的行中访问 整数,一种方法是尽可能继续读取整数。
如果由于某种原因,您发现整数读取失败(例如,因为输入流中有 {),请跳过该单个字符并继续。
示例代码如下:
#include <iostream>
int main() {
int intVal; // for getting int
char charVal; // for skipping chars
while (true) {
while (! (std::cin >> intVal)) { // while no integer available
std::cin.clear(); // clear fail bit and
if (! (std::cin >> charVal)) { // skip the offending char.
return 0; // if no char left, end of file.
}
}
std::cout << intVal << '\n'; // print int and carry on
}
return 0;
}
抄录如下:
pax> echo '{(314159,271828),(42,-1)}' | ./testprog
314159
271828
42
-1
【讨论】: