Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am currently reading the book " Programming Principles and Practice Using " and trying to solve a really simple exercise:

" Write a program that consists of a while -loop that (each time around the loop) reads in two int s and then prints them. Exit the program when a terminating '|' is entered."

I do not know how to formulate the condition to break the while loop

#include "std_lib_facilities.h"

int main()
{   int i = 0,j = 0;
    while()
    {
        cin>>i>>j;
        cout<<i<<j<<endl;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

#include <iostream>
#include <string>
#include <cctype>

int main()
{
    int a = 0, b = 0;
    char term;

    // First solution
    while (true)
    {
        std::cin >> a >> b >> term;
        if(term == '|') break;
        else std::cout << a << ' ' << b << std::endl;
    }
    return 0;

    // Second solution
    while(true)
    {
        std::string line;
        std::getline( std::cin, line );
        if(line.find("|") == line.npos)
        {
            for(int i = 0; i< line.size() && ( std::isdigit(line[i]) || line[i] == ' '); i++)
                std::cout << line[i];
            std::cout << std::endl;
        }else break;
    }
}

IMHO 2'nd option is better if you want to stick to STL, first option should be more readable and easier to understand. If you have any questions, feel free to ask


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...