Home > Enterprise >  How to get integers until \n for n number of lines
How to get integers until \n for n number of lines

Time:10-26

My input : the first input is number of lines the input will contain

5
7 3 29 0
3 4 3 
2 3 4 55 5
2 3
1 2 33 4 5

My issue is how can I store them in vector of vector..?

My concept..

.
.
.
cin>>n;
vector<vector<int>>vec;
while(n--)
{
    vector<int>vec2;
    for(**Getting input until the line**){
    vec2.emplace_back(input);}
    vec.emplace_back(vec2)
}

I need to implement that getting input till the line. For this I thought of getting the input as string and storing the values in vector vec2 using strtok after converting it to c_string... But I need to know whether there is any efficient way I can overcome this problem..

CodePudding user response:

Here's my suggestion, YMMV.

  1. Read each line into a string.
  2. Use istringstream to extract the integers from the string, into a vector.
  3. After string is processed, push_back the vector into the outer vector.
    unsigned int rows;  
    std::cin >> rows;  
    std::string text_row;  
    for (unsigned int i = 0U; i < rows;   i)  
    {  
        std::getline(cin, text_row);  
        std::istringstream numbers_stream(text_row);  
        std::vector<int>  row_data;  
        int number;  
        while (numbers_stream >> number)  
        {  
            row_data.push_back(number);  
        }  
        vec.push_back(row_data);  
    }  
  • Related