EOL in c++(input)

Nov 5, 2011 at 4:42pm
hi guys,i am beginner in c++.i have two question?
1)how to write end of line in input(without getline)for integers?
2)how to end input with 0?
Last edited on Nov 5, 2011 at 4:47pm
Nov 5, 2011 at 4:51pm
You need to use getline() so you can save the data in strings. You can then convert the strings to integers. There's no way to directly read the data as integers.
Nov 5, 2011 at 4:57pm
ok thank you very much ,i got it,and do you know how can end input with 0?
Nov 5, 2011 at 5:01pm
You can use a while loop and set your variable inside the loop to 0. Like so, while(a<=-1||a>=1).
Nov 5, 2011 at 5:05pm
i write like that but it doesnt work
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

int main()
{int a[10],i;
while(a[i]!=0)
cin>>a[i];

    return 0;
}
Last edited on Nov 5, 2011 at 5:05pm
Nov 5, 2011 at 5:08pm
I'm relatively new too. That is the best I've got brother. Keep pushing forward! We can't be new at this forever:)
Nov 5, 2011 at 5:14pm
ok thanks bro))
Nov 5, 2011 at 5:16pm
Are you trying to take input from the keyboard, or from a .txt file?
Nov 5, 2011 at 5:17pm
from keyboard
Nov 5, 2011 at 5:34pm
Aah, then I misunderstood you. I think this code should do what you want:

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

int main()
{
	int a[10], i;

	/* a for loop is just like a while loop, it just uses 'i' to
           control how many times it should go through the loop */
	for(i = 0; i < 10; ++i)
	{
		cin >> a[i]; //read an integer from the keyboard
		if(a[i] == 0) break; //if a[i] is 0, break out from the loop
	}
	//output the content of "a"
	for(int x=0; x <= i; ++x)
		cout << a[x] << endl;

    return 0;
}


As you may see though, there's a limit on how many integers you can enter (10, the maximum size of "a"). If you want to enter an "infinite" amount of numbers without setting a's capacity sky high, you need to use dynamic arrays. I think that may be a little too complicated for you right now though. If there's anything in this code you don't understand, don't hesitate to ask!
Last edited on Nov 5, 2011 at 5:47pm
Nov 5, 2011 at 6:54pm
ohh,it is really what i want .i searched it 1 month ,but couldn't find.thanks very very much for your help
Nov 5, 2011 at 7:35pm
Glad I could help. :)
Last edited on Nov 5, 2011 at 7:35pm
Topic archived. No new replies allowed.