简体   繁体   中英

How do I get a specific number from an input in c++?

Having a list of N ordered pairs of the form (A,B)

Example input:

(200,500)
(300,100)
(300,100)
(450,150)
(520,480)

I want to get only the numbers from the input, so that I can use them within my Point structure, and use them to represent the location on a coordinate plane.

Here is my code:

#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <map>
#include <fstream>
using namespace std;

struct Punto
{
    double x,y;
    double distancia;
    double zona;
};

int main()
{
    int n=4;
    Punto arr[n];

    int x, y;
    for(int i=0; i<n; i++){
      cin.ignore(); //(
      std::cin >> x;
      arr[i].x = x;
      std::cout << "Punto " << i << " x " << x << '\n';
      cin.ignore(); //,
      std::cin >> y;
      arr[i].y = y;
      std::cout << "Punto " << i << " y " << y << '\n';
      cin.ignore(); //)
    }


    return 0;
  }

The problem is that this only works with the first entry but not with the following ones.

ignore will discard a new line delimiter in addition to the characters you want to ignore, this means that in the second iteration of your loop cin.ignore() will ignore a new line character leaving the opening ( still in the stream and causing std::cin >> x to then fail.

A more reliable approach is to read the delimiters and check their values, this will help detect errors in the file format or bugs in your code and has the added bonus that reading the characters will automatically skip whitespace including new lines.

boll readDelim(char expected)
{
    char ch;
    std::cin >> ch;
    return ch == expected;
}

int main()
{
    const int n=4;
    Punto arr[n];

    int x, y;
    for(int i=0; i<n; i++){
      if (!readDelim('(')) break;
      std::cin >> x;
      arr[i].x = x;
      std::cout << "Punto " << i << " x " << x << '\n';
      if (!readDelim(',')) break;
      std::cin >> y;
      arr[i].y = y;
      std::cout << "Punto " << i << " y " << y << '\n';
      if (!readDelim(')')) break;
    }


    return 0;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM