【问题标题】:How to store Integers from a string without using the getline function. C++如何在不使用 getline 函数的情况下存储字符串中的整数。 C++
【发布时间】: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)}

我真的不需要做功课,如果你能给我一个例子,我会很感激的。 谢谢你。

【问题讨论】:

    标签: string input getline


    【解决方案1】:

    如果您只想从这样的行中访问 整数,一种方法是尽可能继续读取整数。

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

    示例代码如下:

    #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
    

    【讨论】:

    • 太棒了!!我正在玩它以适应我的代码,因为我必须翻译成矩阵!谢谢,非常感谢,我不知道您可以使用 (! (std::cin >> intVal)) 之类的东西来测试它是整数还是字符!再次!谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多