i need a function like cin.getline() for the number arrays not the charachters?

i need a function works just like cin.getline() for the number arrays not the charachters?
Last edited on
What do you mean by "number arrays"?

Something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int main()
  {
  vector <int> xs;
  
  string s;
  if (!getline( cin, s )) return 1;

  istringstream ss( s );
  copy( 
    istream_iterator <int> ( ss ), 
    istream_iterator <int> (), 
    back_inserter( xs )
    );
  if (!ss.eof()) return 2;

  return 0;
  }

Caveat: I just typed this in off the top of my head. Small errors may have occurred.

Hope this helps.
No.
For example i use this
1
2
 for(int i=0;i<10;i++)
   cin.getline(name[i],n);//name is char array,n is a aparameter. 

This code make the program ignore spaces and if i pressed enter with out entering any element ,the compiler reads that blank entery as one and print it's place a blanke space.
I just wont a function can do this but with an array of numbers... i hope that u get it.
I think I better understand you. You want to
(1) read a number (like int) as single input from user, where if user just presses Enter key the number read is assumed to be 1
(2) use this in a loop to fill an array

Is this more like what you want?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <sstream>
#include <string>

// Reading a single integer from input with validation is a little more 
// complex than you would think. This is the simplest possible way.
int getline_number( istream& ins, int Default = 1 )
  {
  // Read a line terminated by ENTER|NEWLINE from the argument stream
  string s;
  getline( ins, s );

  // Get rid of any trailing whitespace
  s.erase( s.find_last_not_of( " \f\n\r\t\v" ) + 1 );

  // Try to convert the input into a valid number
  istringstream ss( s );
  int result;
  ss >> result;

  // Validate 
  if (!ss.eof()) return Default;

  return result;
  }

int main()
  {
  int numbers[ 10 ];

  cout << "Please enter ten numbers, one per line.\n";

  for (int i=0; i<10; i++)
    {
    numbers[i] = getline_number( cin );
    }

  cout << "Good job. The numbers are:\n";
  for (int i=0; i<10; i++)
    {
    cout << numbers[i] << "\n";
    }

  return 0;
  }

Hope this helps.

[edit] fixed "default" to "Default"
Last edited on
Topic archived. No new replies allowed.