Why is my program not working when I enter a charge number that matches the number in my array. Please Refer to the function
#include <iostream>
#include <cmath>
using namespace std;
string returnWord(int arr[], int SZ)
{
int nums = 0;
string answer;
cout << "Please enter a charge number: ";
cin >> nums;
for (int i = 0; i < SZ; i ) {
if (nums == arr[i]) {
answer = "This is Valid";
}
else {
answer = "This is Invalid"; // When I enter the valid number this is what prints out
}
}
return (answer);
}
int main()
{
const int SZ = 18;
int nums[SZ] = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850,
8080152, 4562555, 5552012, 5050522, 7825877, 1250255,
1005231, 6545231, 3852085, 7576651, 7881200, 4581002 };
string something = returnWord(nums, SZ);
cout << something << " ";
}
My program when ran will not properly print out "This is valid", even when I enter the correct number from my array. I don't understand why this is happening.
CodePudding user response:
It will only print This is Valid
if the last number in the array is valid because you continue the loop through the whole array and assign answer
in each step.
You should return from the function early if the value you check is valid or return that it's invalid after the loop.
Example:
std::string returnWord(int arr[], size_t SZ) {
cout << "Please enter a charge number: ";
if (int nums; cin >> nums) {
for (size_t i = 0; i < SZ; i ) {
if (nums == arr[i]) {
return "This is Valid"; // return directly when it's found valid
}
}
}
return "This is Invalid"; // the whole array is checked, it was invalid
}
CodePudding user response:
This for loop with the inner if statement
for (int i = 0; i < SZ; i ) {
if (nums == arr[i]) {
answer = "This is Valid";
}
else {
answer = "This is Invalid"; // When I enter the valid number this is what prints out
}
}
is logically incorrect. It can be interrupted at once when the current element of the array is not equal to the searched number.
Rewrite the loop for example the following way
std::string returnWord( const int arr[], size_t SZ )
{
int nums = 0;
std::cout << "Please enter a charge number: ";
std::cin >> nums;
size_t i = 0;
while ( i != SZ && nums != arr[i] ) i;
return i == SZ ? "This is Invalid" : "This is Valid";
}