簡體   English   中英

C ++ Stringstream將錯誤的值賦給變量?

[英]C++ Stringstream assigning wrong value to variable?

我在這里有這段代碼

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

當在終端輸入“ 1 2”時,cout打印輸出:

Player 1 enter coordinate
1 2  //input

1 4197944 //output

難道我做錯了什么?

字符串“ s”僅檢索第一個單詞“ 1”。 不必煩惱stringstream,您可以直接使用標准輸入流。

cin >> x
cin >> y

我必須使用getline()而不是cin,因為cin以空格結尾。

固定版本:

    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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM