C++/c++

Advertisement


Question
platfom:microsoft visual c++ 6.0
I wish to a write a program which for a sequence of numbers tells me how many times the first number occurs. E.g 1 5 7 1 6 8 1  it would output 3. Here is my attempt what am I doing wrong.
#include <iostream>
using namespace std;
int main(){
bool finished = false;
 int num1;
int count=0;
 cin>>num1;
while ( ! finished){
int num;
cin >> num;
         
if ( cin.fail() )
finished = true;
else if(num==num1)
count=count+1;          else cout<<count<<endl;
     
    }
     
return 0;}  

Answer
1. you should initialize count to 1 (int count=1;), because you have already read the first number.
2. you should write count after while loop (before return comman).
3. because you have used cin.fail(), you should intrrupt the standard input to get a fail. For instance press Ctrl-Z and then Enter.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Sam

Expertise

You may ask me about simple to complicated C/C++ programming methods/style and most like questions about network programming in C++.

Experience

I'm a professional programer in C++ and network/internet programming.

©2016 About.com. All rights reserved.