Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c++ - Exit while loop when character | is entered

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

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

1 Reply

0 votes
by (71.8m points)
#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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...