inputing a stream of unknown no of integers, and making integer operatins on it

65 views Asked by At
#include<stdio.h>
#include<conio.h>
#include<iostream>

using namespace std;

main()
{

 int n;

 char arr[50];

 gets(arr);

//the entered integers are in the array. i rechecked.

//now, to find the number of integers,... i tried these methods:

//the input i used was 5 45 25 15 5 25


 size = sizeof(arr)/sizeof(*arr); //here o/p is wrong.

 length = 0;
 while (true)
 {
    if (yo[length] == '\0')
        break;
    else
        length++;
 }
 cout<<length; // here the o/p is wrong.

//i also tried using strlen operation, but the answear is wrong.

//how else can i get the o/p as 6 ?? 

}

now, i tried searching online for answears and many mentioned vectors, but then i tried learning it. if vectors is the only way, can you then write out a program, which gets the numbers like a line input and then converts them into an array,(like phps explode function) and then count the number of elements??

and let it work for the input " 5 15 25 35 15 5 " like that..

2

There are 2 answers

2
fjardon On BEST ANSWER

In order to read an integer you should use the >> operator.

int n;
vector<int> v;

while(cin >> n)
    v.push_back(n);

After that, the vector v contains the list of integers and you can query the number of integers using: v.size().

See:

By the way, I see you use conio.h and stdio.h, please tell what compiler you use, I didn't see these headers since the days of TurboC++ 3.0

For a modern compiler you should include: <iostream> and <vector>

3
user4581301 On

Just gets the count. The input values are discarded.

int count = 0;
int val;
while (cin >> val)
{
    count++;
}