473,287 Members | 1,426 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Reading in a variable number of integers with cin

H.
I'm writing a driver for something I wrote, and can't remember how to
do this very simple thing. The code I have at this point in time:

int myArr[100];
int temp;
int ind = 0;
cout << "enter some integers: ";
while (cin >> temp)
{
myArr[ind++] = temp;
}

The problem is that it doesn't exit until the user enters a non-number.
It won't exit if the user simply hits enter.

What I'm trying to create is something that allows the user to separate
values by spaces, and press the Enter key when done entering them. A
variable number of items will be separated by spaces, e.g.:
"Enter the integers to be sorted with spaces between them and Enter to
finish"

Feb 6 '06 #1
11 5419

H. wrote:
I'm writing a driver for something I wrote, and can't remember how to
do this very simple thing. The code I have at this point in time:
The code you posted doesn't compile.
Please make sure you post compilable code here if you want help.
int myArr[100];
How do you know 100 is a good value? What if I want to enter 101
numbers?
Use a std::vector instead to keep your options open.
int temp;
Always initialize your variables.
int ind = 0;
cout << "enter some integers: ";
while (cin >> temp)
{
myArr[ind++] = temp;
At index 101, this will blow ;)
}

The problem is that it doesn't exit until the user enters a non-number.
It won't exit if the user simply hits enter.

What I'm trying to create is something that allows the user to separate
values by spaces, and press the Enter key when done entering them. A
variable number of items will be separated by spaces, e.g.:
"Enter the integers to be sorted with spaces between them and Enter to
finish"


I'm probably doing your homework for you here, but I'll hope that the
sorting algorithm is the real challenge here.

Here's some code for you to work with:
#include <iostream> // std::cout, std::endl
#include <string> // std::string
#include <sstream> // std::stringstream
#include <vector> // std::vector
#include <algorithm> // std::copy
#include <iterator> // std::ostream_iterator

int main()
{
std::cout << "Enter integers separated by spaces:\n";

std::string line;
if ( std::getline( std::cin, line ))
{
std::stringstream ss( line );
std::vector<long> values;
long l = 0;

while( ss >> l )
values.push_back( l );

if ( values.size() )
std::copy( values.begin(), values.end(),
std::ostream_iterator<long>(std::cout, "\n"));
}
}

Cheers,
Andre

Feb 6 '06 #2
H.
Thanks for all that, it was very educational. (Unfortunately, It's an
overkill for what I'm trying to do, but again, thanks though.) Vectors
are great; they can't be used for what I'm doing, arrays are needed.)
And hard-coding the array number to 100 is fine for the testing driver
I'm writing; there will never be 101 numbers. Basically the goal is to
create something as simple as possible to get the job done, with no
extra classes besides iostream. It is being used as a driver for a
homework problem, but I already created a simpler driver that hard
codes the number of entries, which is good enough for the assignment at
hand, since the assignment is not about the numbers but manipulating
them in a given way with recursion. Actually, for the driver, I could
skip the user input altogether and just feed the recursive function all
of the test lists, and so in that sense, it's not a homework problem at
all, just a "for my edification" problem. I'll figure it out, because
I'm sure it can't really be that hard a thing to do.

in*****@gmail.com wrote:
H. wrote:
I'm writing a driver for something I wrote, and can't remember how to
do this very simple thing. The code I have at this point in time:


The code you posted doesn't compile.
Please make sure you post compilable code here if you want help.
int myArr[100];


How do you know 100 is a good value? What if I want to enter 101
numbers?
Use a std::vector instead to keep your options open.
int temp;


Always initialize your variables.
int ind = 0;
cout << "enter some integers: ";
while (cin >> temp)
{
myArr[ind++] = temp;


At index 101, this will blow ;)
}

The problem is that it doesn't exit until the user enters a non-number.
It won't exit if the user simply hits enter.

What I'm trying to create is something that allows the user to separate
values by spaces, and press the Enter key when done entering them. A
variable number of items will be separated by spaces, e.g.:
"Enter the integers to be sorted with spaces between them and Enter to
finish"


I'm probably doing your homework for you here, but I'll hope that the
sorting algorithm is the real challenge here.

Here's some code for you to work with:
#include <iostream> // std::cout, std::endl
#include <string> // std::string
#include <sstream> // std::stringstream
#include <vector> // std::vector
#include <algorithm> // std::copy
#include <iterator> // std::ostream_iterator

int main()
{
std::cout << "Enter integers separated by spaces:\n";

std::string line;
if ( std::getline( std::cin, line ))
{
std::stringstream ss( line );
std::vector<long> values;
long l = 0;

while( ss >> l )
values.push_back( l );

if ( values.size() )
std::copy( values.begin(), values.end(),
std::ostream_iterator<long>(std::cout, "\n"));
}
}

Cheers,
Andre


Feb 6 '06 #3
I am not sure if I understand what you want but I think typing Ctrl-d
on the unix terminal should end the while loop.

Is that what you want?
H. wrote:
I'm writing a driver for something I wrote, and can't remember how to
do this very simple thing. The code I have at this point in time:

int myArr[100];
int temp;
int ind = 0;
cout << "enter some integers: ";
while (cin >> temp)
{
myArr[ind++] = temp;
}

The problem is that it doesn't exit until the user enters a non-number.
It won't exit if the user simply hits enter.

What I'm trying to create is something that allows the user to separate
values by spaces, and press the Enter key when done entering them. A
variable number of items will be separated by spaces, e.g.:
"Enter the integers to be sorted with spaces between them and Enter to
finish"


Feb 6 '06 #4
If you want to keep the user input part you can do something like below
#include <string>
#include <sstream>
#include <iostream>

int main()
{
std::string inp;
int temp(0);

while (std::cin >> inp)
{
if ((inp == "q") ||(inp == "Q"))
{
break;
}
std::istringstream i(inp);
if (!(i >> temp))
{
std::cerr << "Invalid item entered: " << inp << std::endl;
}
// add number here to your array
}
return 0;
}

Feb 6 '06 #5
In article <11*********************@f14g2000cwb.googlegroups. com>,
"H." <hb****@gmail.com> wrote:
Thanks for all that, it was very educational. (Unfortunately, It's an
overkill for what I'm trying to do, but again, thanks though.) Vectors
are great; they can't be used for what I'm doing, arrays are needed.)
Then it must be a homework assignment.
Basically the goal is to
create something as simple as possible to get the job done, with no
extra classes besides iostream.


What 'int2str' provided was pretty simple. What do you have against
using the tools the language provides?

Your requirements were to enter a series of numbers separated by white
space and ending with the return/enter key. The code he provided does
exactly that. If you want a simpler solution, I suggest you pose a
simpler problem.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 6 '06 #6
<in*****@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
: Here's some code for you to work with:
: #include <iostream> // std::cout, std::endl
: #include <string> // std::string
: #include <sstream> // std::stringstream
: #include <vector> // std::vector
: #include <algorithm> // std::copy
: #include <iterator> // std::ostream_iterator
:
: int main()
: {
: std::cout << "Enter integers separated by spaces:\n";
:
: std::string line;
: if ( std::getline( std::cin, line ))
: {
: std::stringstream ss( line );

Here:
: std::vector<long> values;
: long l = 0;
:
: while( ss >> l )
: values.push_back( l );

Since you already use ostream_iterator for output,
how about using the single statement:
std::vector<long> values
( std::istream_iterator<long>( ss )
, std::istream_iterator<long>() );

: if ( values.size() )
: std::copy( values.begin(), values.end(),
: std::ostream_iterator<long>(std::cout, "\n"));
: }
: }
:
: Cheers,
: Andre

.... only for the sake of consistency/completeness,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Feb 6 '06 #7
In article <11**********************@g43g2000cwa.googlegroups .com>,
"H." <hb****@gmail.com> wrote:
I'm writing a driver for something I wrote, and can't remember how to
do this very simple thing. The code I have at this point in time:

int myArr[100];
int temp;
int ind = 0;
cout << "enter some integers: ";
while (cin >> temp)
{
myArr[ind++] = temp;
}

The problem is that it doesn't exit until the user enters a non-number.
It won't exit if the user simply hits enter.

What I'm trying to create is something that allows the user to separate
values by spaces, and press the Enter key when done entering them. A
variable number of items will be separated by spaces, e.g.:
"Enter the integers to be sorted with spaces between them and Enter to
finish"


void fn( vector<int>& myArr )
{
cout << "enter some integers: ";
string line;
if ( getline( cin, line ) )
{
myArr.clear();
stringstream ss( line );
copy( istream_iterator<long>( ss ), istream_iterator<long>(),
back_inserter( myArr ) );
}
}

Note, with the above: if the user enters a non-numeric char then the
vector will be loaded up to that point but not after. If you want it to
skip incorrect input, then I suggest going through the line first
looking for non-digits...

bool is_digit( char c ) {
return isdigit( c );
}

// after "myArr.clear();"
replace_if( line.begin(), line.end(),
not1( ptr_fun( &is_digit ) ), ' ' );

I have a question... I was unable to put isdigit directly into the
ptr_fun (I had to wrap it.) Any help there?

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 6 '06 #8
In article <ds**********@news.hispeed.ch>,
"Ivan Vecerina" <IN*****************@ivan.vecerina.com> wrote:
<in*****@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
: Here's some code for you to work with:
: #include <iostream> // std::cout, std::endl
: #include <string> // std::string
: #include <sstream> // std::stringstream
: #include <vector> // std::vector
: #include <algorithm> // std::copy
: #include <iterator> // std::ostream_iterator
:
: int main()
: {
: std::cout << "Enter integers separated by spaces:\n";
:
: std::string line;
: if ( std::getline( std::cin, line ))
: {
: std::stringstream ss( line );

Here:
: std::vector<long> values;
: long l = 0;
:
: while( ss >> l )
: values.push_back( l );

Since you already use ostream_iterator for output,
how about using the single statement:
std::vector<long> values
( std::istream_iterator<long>( ss )
, std::istream_iterator<long>() );

For that matter, copy will work:

copy(istream_iterator<long>(ss), istream_iterator<long>(),
back_inserter(values));
: if ( values.size() )
The above 'if' is unnecessary. Should values.begin() and values.end() be
equal, copy will do the right thing.
: std::copy( values.begin(), values.end(),
: std::ostream_iterator<long>(std::cout, "\n"));
: }
: }
:
: Cheers,
: Andre

... only for the sake of consistency/completeness,
Ivan


--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 6 '06 #9

H. wrote:
And hard-coding the array number to 100 is fine for the testing driver
No, it's not fine. Not even for testing.
I'm writing; there will never be 101 numbers.


I don't believe you. Or to put it another way, there is no guarantee
that there will "never" be 101 numbers.
To look at your code snipper again:
while (cin >> temp)
{
myArr[ind++] = temp;


This simply contradicts you. With the while loop being what it is,
there in fact CAN be 101 numbers. If you want to GUARANTEE that there
will NEVER be 101 numbers, then have the code do the talking:

while( cin >> temp && ind < 100 )
....

And of course us a constant value instead of a magic number.

Whenever you declare an array of fixed size, you need to make 100% sure
that it cannot go out of bounds. Make it a habbit.

Cheers,
Andre

Feb 6 '06 #10
H.

Whenever you declare an array of fixed size, you need to make 100% sure
that it cannot go out of bounds. Make it a habbit.


Good point, thanks.

Feb 6 '06 #11

H. wrote:
the assignment is not about the numbers but manipulating
them in a given way with recursion.


You know, especially if the assignment isn't about array handling
itself, then you should go with a vector. You can access the elements
in a vector just like in an array (ex. my_vect[1]). So the "meat" of
your code (your recursive function) wouldn't look much different
whether you used arrays or a vector.

Cheers,
Andre

Feb 6 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: bas | last post by:
hey, I am having a lot of trouble trying to get this program to work properly. It is supposed to read integers from a file and place them into the categories for inventory. The problem seems to...
4
by: Fred West | last post by:
I have a class with a private Int32 data member that gets modified from multiple background threads. To synchronize these modifications I use the lock statement: Int32 count = 0; object...
4
by: Peter | last post by:
I run into this situation all the time and I'm wondering what is the most efficient way to handle this issue: I'll be pulling data out of a data source and want to load the data into an array so...
1
by: Rob | last post by:
Hi. I want to write code to input N integers from a line of a file. It should give an error if it encounters a newline before N integers are read, and also give an error if a newline is not...
3
by: carvalho.miguel | last post by:
hello, imagine you have a static class method that receives a function pointer, an int with the number of arguments and a variable number of arguments. in that static method you want to call...
29
by: garyusenet | last post by:
I'm trying to investigate the maximum size of different variable types. I'm using INT as my starting variable for exploration. I know that the maximum number that the int variable can take is:...
10
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the...
11
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function...
4
by: C++ Newbie | last post by:
Suppose I have a text file with the input: 1 2 3 4 5 6 7 8 9 10 ! Comment: Integers 1 - 10 How do I write a C++ program that reads in this line into a 10-element vector and ignores the...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.