I'm trying to solve an exercise here. First part of it was about feeding a programm 10 numbers and sorting them, which you can see below. However that used a method of assigning each input to an array individually with a loop. But now exercise asks to make a single input of several numbers instead of number->enter. So that makes input factor random (as i won't know how many number are written).
So I can't seem to figure out how to create a proper string of numbers from input that program can deal with later =(
I checked Dynamic memory chapter here on the site, but not getting anywhere for now. Can this even be dealt with in other ways?
Thanks!
One approach would be to use std::getline() to read the whole line in one go into a std::string, then use the string you obtained to intialize a std::istringstream and then read the int values from it.
Yes - it suggests that 0 is used as the termination condition. So you just need a while loop which terminates (getting numbers one at a time with cin) when the number is 0.
No need for getline() or istringstream.
Andy
PS If you're using an array, make sure the while loop termination condition also accounts for the array size.
I see, that's what I couldn't do from the very start so I thought there was another way (getline and istringstream did work nicely).
So I need a while loop that places numbers from cin individually in an array and stops when the number is 0. As a matter of fact I think it has to be a do while loop. And then I can start working with integer values of said array.
#include <iostream>
int main()
{
const std::size_t MAX_SZ = 1000 ; // size of the array
int array[MAX_SZ] = {0} ;
std::size_t n = 0 ; // number of integers entered by the user
std::cout << "enter a series of numbers, end the input with 0\n" ;
int value ;
for( ; n < MAX_SZ && std::cin >> value && value != 0 ; ++n ) array[n] = value ;
std::cout << "the " << n << " numbers are: [ " ;
for( std::size_t i = 0 ; i < n ; ++i ) std::cout << array[i] << ' ' ;
std::cout << "]\n" ;
}
> What is size_zt in this code ? A variable that only applies to size of array?
std::size_t is some unsigned integer type that can store the maximum size of a theoretically possible object of any type (including array). std::size_t is commonly used for array indexing and loop counting. http://en.cppreference.com/w/cpp/types/size_t
> Is putting cin inside a loop makes it extract individual values one by one from a line of input numbers?
std::cin >> value returns (a reference to) std::cin; we can test if the read was successful by using this result in a boolean context.
This operator makes it possible to use streams and functions that return references to streams as loop conditions, resulting in the idiomatic C++ input loops such as
while(stream >> value) {...} or while(getline(stream, string)){...}.