Pregunta

I have this section of code here

    cout << "Player 1 enter coordinate" << endl;
    int x, y;
    string s;
    cin >> s;
    stringstream is(s);
    is >> x >> y;
    cout << x << " " << y << endl;

When enter "1 2" into the terminal, cout prints out:

Player 1 enter coordinate
1 2  //input

1 4197944 //output

Am I doing something wrong?

¿Fue útil?

Solución 2

I had to use getline() instead of cin, since cin ends at whitespace.

Fixed version:

    std::cout << "Player 1 enter coordinate" << std::endl;
    int x, y;
    std::string s;
    std::getline(std::cin,s);
    std::stringstream is(s);
    is >> x >> y;
    std::cout << x << " " << y << std::endl;

Otros consejos

The string 's' is only retrieving the first word '1'. Instead of bothering with stringstream, you can just use standard input stream directly.

cin >> x
cin >> y
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top