Hello,
My problem is that the program always gives the same output:
There were no matching numbers !!!
The source of my program looks as follows:
#include <iostream>
using namespace std;
int main(void)
{
const int MAX_CHARS = 500;
const int MAX_NUMS = 5;
const int MAX_NUM_CHARS = 25;
char values_input[MAX_CHARS];
char number_to_find[MAX_NUM_CHARS];
char num[MAX_NUM_CHARS];
char chr_digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\0'};
int value_array[MAX_NUMS] = {0}; // initialize to zero
int value_pos_array[MAX_NUMS] = {0}; // initialize to zero
cout << "Enter " << MAX_NUMS << " values: ";
cin.getline(values_input, MAX_CHARS);
cout << endl;
cout << "Enter a number to search: ";
cin.getline (number_to_find, MAX_NUM_CHARS);
/* Save the user input in an array */ // I think the error is in this part
for(int i = 0; i < MAX_CHARS; i++)
{
for(int j = 0; j < 10; j++)
{
if (values_input[i] == chr_digits[j])
{
// we read a normal number
// add the character to the num c-string
num[j] = values_input[i];
} else if (values_input[i] == ' '){
// we read a space
// store the final number and reset num
value_array[j] = atoi(num);
//num = '';
} else {
// we read an 'unknown' character
}
}
}
/* Count the position(s) of number_to_find */
int count_match = 0;
for(int i = 0; i < MAX_NUMS; i++)
{
if (value_array[i] == atoi(number_to_find))
{
count_match++; // increment by one
value_pos_array[i] = i; // store the position of the number
}
}
/* Display the result on the screen */
if(count_match == 0)
{
// no numbers found
cout << "There were no matching numbers !!!" << endl;
} else {
// matching numbers were found
// display the positions of those numbers on the screen
cout << "Found " << count_match << " match(es)" << endl;
cout << "On the following positions: ";
for(int i = 0; i < MAX_NUMS; i++)
{
if(value_pos_array[i] == 0)
{
// all the positions of the searched number have been displayed
cout << endl;
} else {
// display the following position on the screen
cout << value_pos_array[i];
if(value_pos_array[i] != 0)
{
cout << ", ";
}
}
}
}
return 0;
}
I wrote this program because I tried to address the problem described in the following thread: http://www.daniweb.com/forums/thread178893.html
Thanks in advance!