'|'와 같은 지정된 문자로 입력 스트림을 종료 하시겠습니까?

Aug 21 2020

현재 C ++을 배우고 있습니다.

입력을 '|'로 끝낼 때 문제가 있습니다. 문자, 내 프로그램은 끝 / 끝으로 건너 뛰고 추가 입력을 허용하지 않습니다. 나는 int를 기대할 때 char 입력으로 인해 std :: cin이 오류 상태에 있기 때문에 std :: cin.clear () 및 std :: cin.ignore ()를 사용하여 문제를 해결하고 나머지 프로그램이 실행되도록 허용하지만 여전히 크래킹 할 수없는 것 같습니다. 어떤 조언도 감사하겠습니다.

int main()
{
    std::vector<int> numbers{};
    int input{};
    char endWith{ '|' };

    std::cout << "please enter some integers and press " << endWith << " to stop!\n";
    while (std::cin >> input)
    {
        if (std::cin >> input)
        {
            numbers.push_back(input);
        }
        else
        {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max());
        }
    }

그런 다음 벡터를 함수에 전달하여 x 번 반복하고 각 요소를 합계에 추가하지만 프로그램은 항상 사용자 입력을 건너 뜁니다.

std::cout << "Enter the amount of integers you want to sum!\n";
    int x{};
    int total{};
    std::cin >> x;


    for (int i{ 0 }; i < x; ++i)
    {
        total += print[i];
    }

    std::cout << "The total of the first " << x << " numbers is " << total;

도와주세요!

답변

1 JohnnyMopp Aug 21 2020 at 01:54

용도에 "|"를 입력하면 (또는이 아닌 모든 것 int) 루프가 종료되고 루프 내부의 오류 처리가 실행되지 않습니다. 오류 코드를 루프 외부로 이동하십시오. 또한 stdin다른 모든 int를 건너 뛰는 두 번 읽습니다 .

while (std::cin >> input) {
    numbers.push_back(input);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

참고 : "|"를 구체적으로 확인하려는 경우 다음과 같이 변경할 수 있습니다.

while (true) {
    if (std::cin >> input) {
        numbers.push_back(input);
    }
    else {
        // Clear error state
        std::cin.clear();
        char c;
        // Read single char
        std::cin >> c;
        if (c == '|') break;
        // else what to do if it is not an int or "|"??
    }
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');