การอัปเดตตัวแปรเดียวกันหลายครั้ง [ซ้ำกัน]

อาจซ้ำกัน:
ปัญหาในการใช้ cin สองครั้ง

รหัสนี้ใช้งานได้ แต่ไม่ใช่สิ่งที่ฉันตั้งใจไว้ ทุกครั้งที่ฉันต้องการป้อนเงินเดือนใหม่โดยการกด 1 ผลลัพธ์ที่ command prompt จะเป็นดังนี้:

Comic books             : USD Input error! Salary must be in positive integer.



โค้ดควรหยุดที่ cout<<"\n\nComic books\t\t: USD "; ที่บรรทัด 4 แต่เพิ่งดำเนินการโดยใช้ while loop ภายใน นี่คือรหัส:

    double multiplePay =0;

    cout<<"\n\nEnter employee pay for each job";
    while (1){
    cout<<"\n\nComic books\t\t: USD ";
    //cin.get(); if enable, the first user input will be 0. this is not working.

    std::string comic_string;
    double comic_double;
    while (std::getline(std::cin, comic_string))
    {
        std::stringstream ss(comic_string); // check for integer value

        if (ss >> comic_double)
        {
            if (ss.eof())
            {   // Success so get out
                break;
            }
        }

        std::cout << "Input error! Salary must be in positive integer.\n" << std::endl;
        cout<<"Employee salary\t: ";
    }

    comic = strtod(comic_string.c_str(), NULL);

        multiplePay = comic + multiplePay; // update previous salary with new user input
        cout << multiplePay;
    cout << "Add other pay?"; // add new salary again?
    int y;

    cin >> y;
    if (y == 1){


        cout << multiplePay;
    }
    else{
        break;
    }
    } // while

cout << multiplePay;  //the sum of all salary

การใช้ cin.get() จะช่วยแก้ปัญหาได้ แต่อินพุตเงินเดือนของผู้ใช้คนแรกจะกลายเป็น 0 และจะคำนวณเฉพาะอินพุตถัดไปเท่านั้น โปรดช่วยฉันด้วยเรื่องนี้ ขอบคุณล่วงหน้า.


person sg552    schedule 22.12.2012    source แหล่งที่มา


คำตอบ (2)


ปัญหาของคุณคือ cin >> y; จะอ่าน int แต่ปล่อยจุดสิ้นสุดของบรรทัด \n ไว้ในบัฟเฟอร์อินพุต ครั้งต่อไปที่คุณใช้ getline มันจะค้นหาจุดสิ้นสุดของบรรทัดนี้ทันที และไม่รออินพุตอีกต่อไป

person Bo Persson    schedule 22.12.2012
comment
ใช่นั่นคือปัญหา การเพิ่ม cin.get() ในส่วนสุดท้าย if statement ช่วยแก้ปัญหาได้ ขอบคุณอีกครั้ง. - person sg552; 22.12.2012

std::basic_ios::eof() (ใน ss.eof()) ไม่ทำงานอย่างที่คุณคิด .

    if (ss >> comic_double)
    {
        if (ss.eof())
        {   // Success so get out
            break;
        }
    }

ss.eof() จะเป็นจริงก็ต่อเมื่อการเรียก ss.get() หรือการแตกไฟล์อื่นล้มเหลวเนื่องจากคุณอยู่ที่ส่วนท้ายของไฟล์ ไม่สำคัญว่าเคอร์เซอร์จะอยู่ท้ายสุดหรือไม่

โปรดทราบว่าคุณแก้ไขปัญหานี้ได้อย่างง่ายดายโดยใช้ ss.get():

    if (ss >> comic_double)
    {
        ss.get(); // if we are at the end ss.eof() will be true after this op

        if (ss.eof())
        {   // Success so get out
            break;
        }
    }
person Zeta    schedule 22.12.2012