Help with Programming please
Feb 3, 2017 at 8:07pm UTC
I have tried running my code, and I think I have set it up right. However it does not wrong. I was wondering what is wrong with it. Here is the prompt:
Prompt the user for an integer value until the value -1 is entered. Print out each of the values entered on its own line before -1 is entered. Do not print out the -1.
Example:
Input:
2
6
4
0
-1
Output:
2
6
4
0
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
#include <iostream>
#include <string>
using namespace std;
int main()
{
//cout << "Please put in a number" << endl;
string number = "user_number" ;
string negative_one = "yeah_NegativeOne" ;
cin >> number;
cin >> negative_one;
if (number.compare("user_number" )>= -1)
{
if (negative_one.compare("yeah_NegativeOne" )>= -1)
{
cout << "user_number" << endl;
}
}
else if (number.compare("user_number" )== -1)
{
if (negative_one.compare("yeah_NegativeOne" )== -1)
{
cout << "-1" << endl;
}
}
return 0;
}
Feb 3, 2017 at 8:48pm UTC
There is no loop to your code to continue to pull in data, also strings are not a very good way to store numbers. I would recommend a vector.
The way I would do this is something like:
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
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int num = 0;
vector<int > nums;
cout << "Please put in a number" << endl;
while (num != -1)
{
cin >> num;
nums.push_back(num);
}
cout << "\n" ;
for (int count = 0; count < (nums.size() - 1); count++)
{
cout << nums[count] << endl;
}
return 0;
}
Even if you don't know how to use vectors hopefully the structure will help give you an idea.
Feb 3, 2017 at 10:04pm UTC
Why cache the numbers at all?
1 2 3 4
# include <iostream>
int main() {
for (int num; std::cin >> num && num != -1; ) std::cout << num << "\n" ;
}
Last edited on Feb 3, 2017 at 10:04pm UTC
Feb 4, 2017 at 12:24am UTC
Thank you all very much it helped!
Topic archived. No new replies allowed.