Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8254063
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T01:04:52+00:00 2026-06-08T01:04:52+00:00

I need to parse a C++ stdin input which looks something like this: N

  • 0

I need to parse a C++ stdin input which looks something like this:

N M (pairs)

0 0
2 1 (0,1)
2 0
5 8 (0,1) (1,3) (2,3) (0,2) (0,1) (2,3) (2,4) (2,4)

If N > 0 && M > 0, then M pairs will follow. It is a single line input so I have no idea how to do it.

I have some solution, but something tells me it’s not the best one.

void input(){
    int a[100][2];
    int n,m;
    char ch;
    cin >> n >> m;
    for ( int i = 0; i < m; i++) {
        cin >> ch >> a[i][0]>> ch>> a[i][1]>>ch;    
    }

    cout << n << " " << m << " \n";

    for ( int i=0; i < m; i++ ) {
        cout << "(" << a[i][0] << " ," << a[i][1] << ")";   
    }
}

My question is what is the best / more correct way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T01:04:53+00:00Added an answer on June 8, 2026 at 1:04 am

    Since input data to applications never can be trusted there is an importance of adding error checks to see that the data provided is indeed valid (otherwise the result of the application might suffer from errors while parsing).

    The “C++ way” of handling errors such as this is to throw an exception when a problem arise in the functions responsible for parsing data.

    The caller of this function will then wrap the call in a try-catch-block to catch errors that might appear.


    With a user-defined-type..

    Defining your own type for holding your pairs of data will greatly improve the readability of your code, the output from the below implementation and the one found later in this post is the same.

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <stdexcept>
    

    struct Pair {
      Pair (int a, int b)
        : value1 (a), value2 (b)
      {}
    
      static Pair read_from (std::istream& s) {
        int value1, value2;
    
        if ((s >> std::ws).peek () != '(' || !s.ignore () || !(s >> value1))
          throw std::runtime_error ("unexpected tokens; expected -> (, <value1>");
    
        if ((s >> std::ws).peek () != ',' || !s.ignore () || !(s >> value2))
          throw std::runtime_error ("unexpected tokens; expected -> , <value2>");
    
        if ((s >> std::ws).peek () != ')' || !s.ignore ())
          throw std::runtime_error ("unexpected token;expected -> )");
    
        return Pair (value1,value2);
      }
    
      int value1, value2;
    };
    

    The one thing I’ve noticed that might be hard for programmers to grasp about the above is the use of s >> std::ws; it’s used to consume available white-spaces so that we can use .peek to get the next non-whitespace character available.

    The reason I implemented a static function read_from instead of ostream& operator>>(ostream&, Pair&) is that the later will require that we create an object before even reading from the stream, which in some cases are undesirable.

    void
    parse_data () {
      std::string line;
    
      while (std::getline (std::cin, line)) {
        std::istringstream iss (line);
        int N, M;
    
        if (!(iss >> N >> M))
          throw "unable to read N or M";
        else
          std::cerr << "N = " << N << ", M = " << M << "\n";
    
        for (int i =0; i < M; ++i) {
          Pair data = Pair::read_from (iss);
    
          std::cerr << "\tvalue1 = " << data.value1 << ", ";
          std::cerr << "\tvalue2 = " << data.value2 << "\n";
        }
      }
    }
    

    Normally I wouldn’t recommend naming non-const variables in only uppercase, but to make it more clear which variable contains what I use the same name as your description of the input.

    int
    main (int argc, char *argv[])
    {
      try {
        parse_data ();
    
      } catch (std::exception& e) {
        std::cerr << e.what () << "\n";
      }
    }
    

    Without the use of user-defined-types

    The straight forward method of parsing the data as well as having checks for errors is to use something as the following, though it could be greatly improved by using User Defined Objects and operator overloads.

    1. read each line using std::getline
    2. construct n std::istringstream iss (line) with the line read
    3. try to read two ints using iss >> N >> M
    4. read M “words” using a std::string s1* with iss >> s1;
      1. Construct a std::istringstream inner_iss using the s1 as initializer
      2. peek to see that the next char available is ( && ignore this char
      3. read integer
      4. peek to see that the next char available is , && ignore this char
      5. read integer
      6. peek to see that the next char available is ) && ignore this char

    If the stringstream isn’t empty after step 4 or iss.good () returns false anywhere inbetween the steps the is a syntax error in the data read.


    Sample implementation

    The source can be found by following the link below (code put elsewhere to save space):

    • ideone.com – example snippet without using user-defined-types

    N = 0, M = 0
    N = 2, M = 1
         value1 = 0, value2 = 1
    N = 2, M = 0
    N = 5, M = 8
         value1 = 0, value2 = 1
         value1 = 1, value2 = 3
         value1 = 2, value2 = 3
         value1 = 0, value2 = 2
         value1 = 0, value2 = 1
         value1 = 2, value2 = 3
         value1 = 2, value2 = 4
         value1 = 2, value2 = 4
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need parse a string inside a parenthesis, which looks like (A, B, C),
I need to parse a line from cmd that looks like this SOME WHITE
Hi I need parse and deserialize pseudo JSON string. Input data: {aBubbleData[ 'jaja2581' ]={
Need to parse a file for lines of data that start with this pattern
I need to parse through a string and add single quotes around each Guid
I need to parse a JSON string in my project, which runs on BB
I need an input file stream which would have a bidirectional iterator/adapter. Unfortunately std::ifstream
I need to parse a file which is in the following format: General {
I need to parse this string into three different components: Location: 1|#69.83623|#24.432223|#Cupertino, California The
I need to parse the server response from my http post & puts. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.