473,385 Members | 1,742 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,385 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 5423

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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.