Need Help

K

Kramer55

I started teaching myself programming over the summer, but have not had
the time.

I recently began to start my programming again, but realized i couldnt
even do a simple problem

create a program that displays how many numbers the user enters

i cant believe i have forgotten how to do something so simple!

without using an array, would it be better to use a for loop or what
would be the best approach?

thank you
 
M

Mike Wahler

I started teaching myself programming over the summer, but have not had
the time.

I recently began to start my programming again, but realized i couldnt
even do a simple problem

create a program that displays how many numbers the user enters

i cant believe i have forgotten how to do something so simple!

without using an array, would it be better to use a for loop or what
would be the best approach?

I'd use a container to store the values. Containers 'know'
their size.

But yes, a loop is another way to do it.
Could be 'for', 'do/while', or 'while'.

IOW, there are a zillion ways to 'skin a cat'. :)

Give it a try, write some code. IF you get stuck, post the
code here and ask specific questions.

One (of many possible) container solution:

#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int main()
{
std::cout << "Please enter a sequence of integers,\n"
"all on one line, separated by whitespace:\n";

std::string line;
std::getline(std::cin, line);

std::vector<int> numbers;
std::istringstream iss(line);

std::copy(std::istream_iterator<int>(iss),
std::istream_iterator<int>(),
std::back_inserter(numbers));

std::cout << "You entered " << numbers.size() << " integers.\n";
return 0;
}



-Mike
 
V

Victor Bazarov

I started teaching myself programming over the summer, but have not had
the time.

I recently began to start my programming again, but realized i couldnt
even do a simple problem

create a program that displays how many numbers the user enters

i cant believe i have forgotten how to do something so simple!

without using an array, would it be better to use a for loop or what
would be the best approach?

A 'while' loop is probably a better choice. Or even a 'do-while' one.
Essentially, the program has to ask the user to enter something. If it
is a number it should increment the counter (initially set to 0) and ask
again. If what was entered is not a number, it should display the number
of numbers entered (the counter) and exit.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,184
Messages
2,570,979
Members
47,580
Latest member
kim2namjoon

Latest Threads

Top