0

Working on a project for a class, where I need to take a number in from the user and perform a task depending on the number. Read in a graph from the command line before taking in the number. The issue is that the cin>> is skipped and doesnt allow the user to enter a number. Ive tried putting cin.clear() and cin.ignore() in a few different places but it didnt seem to help. Included is the relevant code

EDIT: For clarification Im inputting a graph when I run the program like so: ./streets > bel.osm.graph. The code outputs "Enter your number: " and then ends before you can input a number.

    int main(int argc, char *argv[])
{
  string input;
  int colct;
  sparseMat graph;
  readMat(graph, colct); 
  cout << "Enter your number: ";
  cin >> input; //is being skipped
  if(input == "1"){
  cout << "n= " << graph[0][0].getVal() << "; m= " << graph[0][1].getVal() << ".\n";
  }
}

void readMat(sparseMat& graph, int& colct)
{
  colct = 0;
  string line;
  while (getline(cin, line))    // get next full line of text; NB: text
  {
    istringstream lstream(line);
    sparseRow neighbours;
    nz next;
    while (lstream>> next) { // peel off values in this line, one at a time
      neighbours.push_back(next);
    }

    graph.push_back(neighbours);
  }

  cin.clear();
}
Ry3der
  • 1
  • 1
  • What does "cin>> is skipped and doesnt allow the user to enter a number" mean? Where is the standard input coming from? – Sam Varshavchik Apr 27 '21 at 17:01
  • Without sample inputs so that behavior can be observed, you might have a hard time getting help. Nothing jumps out, and usually it's `std::getline()` that gets 'skipped' because people forget the weird ways these two methods of input interact with each other. – sweenish Apr 27 '21 at 17:04
  • `cin.ignore()` consumes only one character. There maybe more than one character in stream buffer. Did you try this syntax: `cin.ignore(numeric_limits::max(), '\n')` – avm Apr 27 '21 at 17:17
  • If `getline(cin, ...)` fails due to the user entering an EOF sequence (CTRL-Z, CTRL-D, etc, depending on platform), that basically means that `cin` can't take in any more input. Calling `cin.clear()` wont fix that. Rather than reading until EOF, I would prompt the user for how many lines are about to be entered, and then break the loop once that many lines have been read. – Remy Lebeau Apr 27 '21 at 17:26

0 Answers0