0

How can I create a function that reads a positive number and returns it, for loops is a must C++

Hey I'm struggling on how to create a function that reads a list full of negative and positive values and it specifically selects the positive values only and returns it how would I make a function off of that

2nd Apr 2021, 10:36 PM
boba
boba - avatar
14 Answers
+ 2
return how a list? anyway: if(number > 0) { // return the number or fill a list }
2nd Apr 2021, 11:14 PM
Alfonso FarĂ­as
Alfonso FarĂ­as - avatar
+ 2
You can use std::vector to make it easier. Then you can use simple if statement to check if value is positive and save it to the vector, you can also return whole vector instead of playing with pointers. So it could be something like this: std::vector<int> positive; int x; while(file >> x) { if (x>0) positive.push_back(x); }
3rd Apr 2021, 12:23 AM
Michal Doruch
0
I may explaines it wrong but lets say the values are 1 -5 3 7 -6 3 its going to return only the positive integers
3rd Apr 2021, 12:04 AM
boba
boba - avatar
0
So the values i listed above is the input file and what I want is that function to read and see which one is positive int ReadANumber(std::ifstream &); This function keeps reading an integer until a non-negative integer is read.  The non-negative integer is returned.  
3rd Apr 2021, 12:08 AM
boba
boba - avatar
0
MichaƂ Doruch i want it as a function inside of this int ReadANumber(ifstream&)
4th Apr 2021, 3:32 PM
boba
boba - avatar
0
Lets say I have a file that includes the following 5 6 7 -5 6 -7 we will call this .txt file where i will call it IFile >> Num i need to make a function that. Only returns a non neg integer
4th Apr 2021, 4:48 PM
boba
boba - avatar
0
I'll wait
5th Apr 2021, 1:30 AM
boba
boba - avatar
5th Apr 2021, 5:31 PM
boba
boba - avatar
0
I am not going to help you until you show your attempt
6th Apr 2021, 1:29 PM
Michal Doruch
0
This may look like it works lol
6th Apr 2021, 3:05 PM
boba
boba - avatar
0
Nees to test it in visual studio
6th Apr 2021, 3:05 PM
boba
boba - avatar
0
You have to name that ifstream reference, when passing it as argument inside function, so it should be: int ReadANumber (ifstream& IFile) Anyway, it will return first positive number only. If you want to return list of numbers, you can for example return pointer: int *ReadANumber (ifstream& IFile) If you want to make it easy, return some other container like vector, as memtioned a few days ago
6th Apr 2021, 3:15 PM
Michal Doruch
0
Ok i just want it to return a positive integer thz
6th Apr 2021, 5:49 PM
boba
boba - avatar