I have been trying to write some code that asks the user for several debit entries for an accounting program. If the user gives 5 as the answer, the program should ask him the debit entry's name and amount 5 times before continuing on to the next line of code. So, I used for loops to solve this problem and it seems something strange is happening.
This is the format in which the code should run when being compiled and executed:
How many debit entries do you wish to make?: 2
1. Debit Entry Name: example1
1. Debit Amount: 123
2. Debit Entry Name: example2
2. Debit Amount: 456
continue on to next line of code
Here's the code I've written in C++ for this part of the accounting program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many debit entries do you wish to make?: ";
int entries;
cin >> entries;
string debitNames[50];
float debitAmounts[50];
int offset = 0;
int number = 1;
for (offset = 0; offset < entries; offset++)
{
cout << number << ". Debit Entry Name: ";
cin >> debitNames[offset];
cout << number << ". Debit Amount: ";
cin >> debitAmounts[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
The outcome is extremely strange, here is what happens when I compile and run it:
How many debit entries to do you wish to make?: 5
1. Debit Entry Name: example1
1. Debit Amount: 123
6. Debit Entry Name: example2
6. Debit Amount : 123
6. Debit Entry Name: example3
6. Debit Amount: 123
6. Debit Entry Name: example4
6. Debit Amount: 123
6. Debit Entry Name: example5
6. Debit Amount: 123
continue on to next line of code
The program, after listing the number as 1, suddenly jumps off to 6 and remains there until all the 5 sets of questions have been asked. As you know by now I'm using the 'number' variable to simply tell the user that 'number' entries have been asked, as specified by the user his/herself. Try running this code in your compiler and see whether the same result appears. By the way, I use Visual C++ 20120 Express Edition, could this have anything do with the problem?
Thanks a lot.
Well, before the loop, you set the number
variable to 1.
Inside the loop, you set the number
variable to (entries + 1)
using this snippet:
for (number = 1; number <= entries; number++)
{
}
Why not simply do this?
cout << (offset + 1) << ". Debit Entry Name: ";