Write your question here.
I'm supposed to obtain a message by getting the first letter of each word from an input sentence of 50 characters or less.
My code works fine if I put everything in the main function, but I'm required to have it in a specific function which I cannot get to work. This is my code with everything from main moved into the function string getSecretMessage(string str)
/**
* Assignment#6.2
* DUE: 3/13/16
* NAME: <Joshua Cisneros>
* Purpose: Your professor needs your help to decipher some secret message in a sentence.
* The secret message is formed by taking the first letter from each word in the sentence,
* in the order they appear. Write the following function per its styling/documentation:
*
*/
#include <iostream>
usingnamespace std;
/**
* FUNCTION SIGNATURE: string getSecretMessage(string str)
* PURPOSE: get secret message by taking the first character from each word in the input sentence, in the order they appear
* PARAMETER:
* str, the input sentence
* RETURN VALUE:
* The secret message
*/
string getSecretMessage(string str)
{
string str[51]; // does not work in this function
int i=0;
for (i=0;i<51;i++)
{
cin >> str[i];
}
for (i=0;i<51;i++)
{
cout << str[i][0];
}
return str;
}
int main (void) {
string str[51]; // the code works perfectly here though.
int i=0;
for (i=0;i<51;i++)
{
cin >> str[i];
}
for (i=0;i<51;i++)
{
cout << str[i][0];
}
return 0;
}
I'm guessing nobody read the top part where I said I'm including my code in both functions, so obviously it's not going to compile.
Isn't an array of strings unnecessary?
There are two main strings - the input sentence, and the output message. Somewhere in the processing, you may need some temporary string to hold an individual word. But it doesn't need to be an array.
1. You are given a string in your getSecretMessage function, so you do not need to take any input in that function.
2. string str[51] that's not how strings work. That just defines an array of 51 strings, not 50 characters plus a null.
3.Error C2082 redefinition of formal parameter 'str' Generic
line: 24
is part of the output I get when I try to compile. You can't have two variables with the same name in the same scope.
4.
1 2 3 4
for (i=0;i<51;i++)
{
cin >> str[i];
}
Now you have to put in 51 words separated by whitespace. Execution won't stop if you input only 25 words. Instead, you can use getline(cin, str); to get exactly one string, however the length could be arbitrarily long. Use a loop in your function that limits you to checking only 50 characters, or you can read in one character at a time (you probably shouldn't) and append them to a string.
You could use a while loop to extract each word in turn. Then get the first letter of that word and concatenate (join) it to the end of the message string. At the end of the function, return the message string.