How to identify a new line in C++?

前端 未结 4 659
猫巷女王i
猫巷女王i 2021-01-25 05:14

I have to take integer input to an integer array. I have to identify the newline also in input. To be more clear, I have an example. The input I am giving is:-

2         


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 05:48

    The istream extraction operator will automatically skip the blank lines in the input, so the read_ints() function in the below example will return a vector of the whitespace (including the newlines) separated values in the input stream.

    #include 
    #include 
    
    using namespace std;
    
    vector
    read_ints(istream & is)
    {
        vector results;
        int value;
        while ( is >> value )
        {
            results.push_back(value);
        }
        return results;
    }
    
    int
    main(int argc, char * argv[])
    {
        vector results = read_ints(cin);
        for ( vector::const_iterator it = results.begin(); it != results.end(); ++it )
            cout << *it << endl;
    
        return 0;
    }
    

    The above code stops reading if any of the input cannot be parsed as an int and allows integers to be separated by spaces as well as newlines, so may not exactly match the requirements of the question.

提交回复
热议问题