user1760072
user1760072

Reputation: 9

A while-loop that reads in two ints and then prints them

I am completely stuck on a drill on chapter 4 of "Programming - Principles and Practice Using C++". The question is:

"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."

This is my code:

{
int entryvariable = 0;
int numberofentries = 0;
vector<int>vector1;


while (cin>>entryvariable)
{
    vector1.push_back(entryvariable);
    ++numberofentries;

if (numberofentries % 2 == 0)
    cout<<vector1[numberofentries - 1] << vector1[numberofentries] << "\n";
}

This, of course, ends up crashing.

How would I fix this so that it works properly?

(Does anyone have an answer key for this book? It's really well written, but it's impossible to check your answers if you're undertaking self-study.)

Upvotes: 0

Views: 1465

Answers (4)

oleg
oleg

Reputation: 11

int main()
{
vector<int>v;
int a=0; 
cin>>a; 
int b=0; 
while (v.size()<2) // insted of 2 it could be another figure for 
                   //   another number of printed figures
{
v.push_back(a); 
cin>>b;
a=b;
}
for (int i=0; i<v.size(); ++i)
cout<<v[i]<<'\n';
}

Upvotes: 1

dee
dee

Reputation: 1

I am working through the same exercises, and have found the google group for the book the best place to ask questions about the exercises and drills, a thread relating to your question can be found here.

Hope this helps.

Upvotes: 0

Anirudha
Anirudha

Reputation: 32817

Your vector1[numberofentries] is causing the error

A vector starts from 0thindex..

So when your numberofentries is 1 ,the value is stored in vector1[0] not vector1[1]

when your numberofentries is 2 ,the value is stored in vector1[1] not vector1[2]

So your code should be

cout<<vector1[numberofentries - 2] << vector1[numberofentries-1] << "\n";

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154025

Indices in C++ are ranging from 0 to n - 1. Your code assumes that you can access vector1[n] if vector1.size() == n. Also, you are only reading one value in each iteration. You can just read two values, though.

Upvotes: 2

Related Questions