spliting integers from input

hi,
i am doing an assignment where i am required to split integers from input line like:
12 12 14 15
here i need to split integers like eg i=12, j=14 etc...
how can i do this, can any1 please help me, by sujjesting any function.
hey try this,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main ()
{
int a , b , c , d;
cout << "Give values to a, b, c and d" <<endl;
cout << "a =  ";
cin >> a;
cout << "b =  ";
cin >> b;
cout << "c =  ";
cin >> c;
cout << "d =  ";
cin >> d;
cout << "\n\n\nThe numbers you inserted are: " <<a <<" " <<b <<" " <<c <<" and " <<d;
system ("pause");
return 0;
}

The output will be like 12 12 14 15 instead of 12121415
just use a space ( cout << " "; between the inputs when you use em as outputs.

Hope it helped ya ^^
Last edited on
thnx for the help but pls next time tel the person think more not just give the answer this will help more.
shammur dont get mad but just show us what u did so we can correct ur errors and tell u where is the error so u ll be more carefull next time to not comit the same mistake ;).

hi nice code but could u pls explain why did u include system ("pause ");
in ur code and what is the benefit thnx :)
Last edited on
thanx to you both, but i think i could not clear my question to you both, actually i am looking for a method/function in Cpp which act like this:
i am giving the same code in java :

int i = Integer.parseInt(s.split(" ")[0]); // first piece becomes an integer
int j = Integer.parseInt(s.split(" ")[1]); // second piece becomes an integer
//
this code is given an input : 1 20 //in same line this input is given
then when the code runs i became 1 and j = 20
One way to do it might be to have the numbers supplied via arguments to the program. This would require it to be run from the console, but it's theoretically cleaner.

1
2
3
4
5
6
C:\Documents and Settings\Peter\My Documents\Code\C++\Learning\Args>console 1 2 3 4
a = 1
b = 2
c = 3
d = 4
a + b + c + d = 10


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>

using namespace std;
int main(int argc, char* argv[])
{
	if (argc <= 4) return 1;
	int a = atoi(argv[1]);
	int b = atoi(argv[2]);
	int c = atoi(argv[3]);
	int d = atoi(argv[4]);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
	cout << "d = " << d << endl;
	cout << "a + b + c + d = " << a + b + c + d << endl;
	return 0;
}
Last edited on
shammur, try using a for loop with the cin>> being iterated according to the number of integers you input. use an array (x[]) to store the inputs. Let the "i" of the loop be the pointer to your array. I think I have tried this before.
thanx every 1 it really helped, and i found a new function
char * strtok ( char * str, const char * delimiters );
Topic archived. No new replies allowed.