Hi everyone,
I am having a problem with a problem I am trying to write. It seems to compile ok, but then when I run it, I get a Segmentation Fault. i am using arrays and I am attempting to return a pointer to a char array and i am not sure if I am doing it correctly. Any help with the below code to figure out why I am receiving this error is greatly appreciated. Thank you very much in advance.
Nick
#include <iostream>
using namespace std;
char* soundex(const char word[]); // prototype
// possibly need '&'
char trade(char);
int main()
{
char inp[40];
for (int i=0; i<10; i++)
{
cout << "Enter a word: ";
cin >> inp[40];
cout << soundex(inp) << "is here" << endl;
}
return 0;
}
// function soundex
// input: a const char[] named word
// output: none
// return: a char array or pointer to the soundex code for that word
char* soundex(const char word[])
{
static char rval[6];
if (trade(word[0]) != 'Z')
rval[0] = word[0];
else
rval[0] = 'Z';
int i = 1;
while (trade(word[i]) != '\n' || i < 5)
{
char tmp = trade(word[i]);
if (trade(rval[i-1]) != tmp)
rval[i] = tmp;
else
rval[i] = '0';
i++;
}
// rval[6] will automatically be changed to \n at the end.
rval[5] = '\n';
return rval;
}
//function trade
// input: char - a letter from the word
// output: none
// return: the soundex translation of the letter
// This is just the function that holds the switch statement
char trade(char c)
{
char ret = '0';
switch(c)
{
case 'b': case 'p': case 'f': case 'v':
case 'B': case 'P': case 'F': case 'V':
ret = '1';
break;
case 'c': case 's': case 'k': case 'g':
case 'j': case 'q': case 'x': case 'z':
case 'C': case 'S': case 'K': case 'G':
case 'J': case 'Q': case 'X': case 'Z':
ret = '2';
break;
case 'd': case 't': case 'D': case 'T':
ret = '3';
break;
case 'l': case 'L':
ret = '4';
break;
case 'm': case 'n': case 'M': case 'N':
ret = '5';
break;
case 'r': case 'R':
ret = '6';
break;
case '\n':
ret = '\n';
break;
default:
ret = 'Z';
break;
}
return ret;
}