如何在不使用getline函数的情况下从字符串中存储整数.C



很抱歉问,但是我一直在寻找一种从这组字符串中提取整数的方法:

{(1,2),(1,5),(2,1),(2,3),(3,2),(3,4),(4,3),(4,5),(5,1),(5,4)}

我真的不需要完成作业,如果您可以将我链接到一个例子,我会很感激。谢谢您。

如果您只想从类似的行访问 Integers ,则一种方法是只需继续读取整数。

如果出于某种原因,您发现整数读取失败(例如,因为输入流中有一个{(,请跳过该字符并继续前进。

示例代码是:

#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

相关内容

最新更新