I have a problem that I am having trouble implementing in c++. I have summarized it below:
The problem: Implementing a linear search typing program to build a full string and return it.
- Iterate through an array containing each Alpha character,' ', '.', '!'
- Ask user if the current array element is the one they have in mind
- if user input is yes, concatenate that element to 'result' above, restart loop
- If user input is '!' output resulting string
My program is not producing any output, so I know I am doing something wrong, but I am very fresh to c++ and I am having trouble identifying potential bugs. The code produces no errors or warnings as is. I wasn't entirely sure of what sections of the code would be most important so I included it all.
Here is my code thus far:
#include <iostream>
#include <string>
using namespace std;
char linearSearch(char arr[], int n, char x)
{
int i;
for (i = 0; i < n; i++)
if (x == 'y')
return i;
if (x == '!')
return -1;
if (i > n)
i = 0;
return 0;
}
// Driver code
int main()
{
char arr[] = {
' ', '.', '!', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
char x;
int n = sizeof(arr) / sizeof(arr[0]);
int i;
i = 0;
cin >> x;
string result_str;
result_str = " ";
while (i < n)
{
i++;
cout << "Are you thinking of the letter:" << arr[i] << '?';
result_str += arr[i];
}
// Function call
char result = linearSearch(arr, n, x);
cout << "You typed:" << result_str;
return 0;
}
Does anyone have any comments or thoughts? I'd really appreciate it! It is important for me to understand where I am going wrong here. I have been trying to debug this for a day or two and I am feeling defeated, but determined to figure this out today!