c++

Input: 1 2 88 42 99

Desired Output: 1 2 88

When 42 is entered in the above code, the code within the while statement still executes .... WHY ?? How Can I reach my desired answer ??


1
2
3
4
5
6
7
8
9
10
11
 int main()
{
    int input{};
    while (input != 42)
        {
            std::cin >> input;
            std::cout << '\n';
        }
    return 0;

}
Define "output". You never print any numbers. The only numbers that will be visible are the ones from standard input.

The code within the while loop will always be executed at least once because input is initially 0 on line 3.
Last edited on
1
2
3
4
5
6
7
#include <iostream>
 int main()
{
    int input{};
    while (std::cin >> input && input != 42)  std::cout << input << " ";
    std::cout.put('\n');
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
   string str;
   getline( cin, str );
   stringstream ss( str );
   for ( int input; ss >> input && input != 42; cout << input << ' ' );    
}
1 2 88 42 99
1 2 88  
When 42 is entered in the above code, the code within the while statement still executes

It doesn’t.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <sstream>


int main()
{
    int input {};
    std::istringstream iss { "1 2 88 42 99" };
    while (input != 42)
    {
        iss >> input;
        std::cout << input << '\n';
    }
}


Output:
1
2
88
42

Following Enoizats example
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <sstream>


int main()
{
    int input {};
    std::istringstream iss { "1 2 88 42 99" };
    while (iss >> input && input != 42)
        std::cout << input << '\n';
}


Output:

1
2
88
Last edited on
Topic archived. No new replies allowed.