Jump to content

Beginner question regarding a "Programming principles and practice" exercise

- - - - -

  • Please log in to reply
1 reply to this topic

#1
bgardner

bgardner

    Newbie

  • Members
  • Pip
  • 8 posts
I'm independently reading the book "Programming Principles and Practice Using C++" and I have a question for you all. I'm in chapter 4 of the book currently and have successfully done the drills, minus one part. It's actually in step 1 of the drill. Step 1 states

Quote

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

now the code starts out with


int val1=0;

int val2=0;


while(cin>>val1>>val2){


[INDENT]//code here[/INDENT]

}


sorry i didn't put everything, I just wanted to abbreviate it and make it short just to give an idea of how it goes. Thing is, when reading in integers and doubles, the program ends simply with anything thats NOT a number. So how would I exit a while-loop such as that with only the "|" character??

Maybe thats a dumb question but i'm just kind of not seeing the answer.

#2
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
  • Programming Language:Java, C#, PHP
  • Learning:C, C++, C#, PHP, Transact-SQL, Assembly, Scheme
Try this:


while(true){
  char c = cin.peek();
  if (c == '|') break;
  int val1, val2;
  cin >> val1 >> val2;
   // code here
}

The idea is look at the next character in the input stream and if it is | then terminate the loop. Otherwise, read two ints and do something with them. Didn't test it but it should work.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users