Display Problem

The code works just fine except for one small problem. Basically it takes the first letter of every word inputted and creates a new word with those letters.
My problem is this: if the user inputs nothing or just a bunch of spaces
it should display ""
instead my code can only display " ". (I know but the professor has his reasons I guess)

Any help?


#include <iostream>

using namespace std;

string getSecretMessage(string str)
{
cout << "Secret Message: ";
cout << '"' << str[0];


for(int i = 0; i < str.length(); i++)
{
if (str[i] == ' ' && str[i+1]!= ' ')
{
cout << str[i+1];
}
}
cout << '"' << endl;

return str;
}

//Main Function
int main()
{
string str;

cout << "Input str: ";
getline(cin, str);
getSecretMessage(str);


return 0;
}
Hello donda97,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Played with your program a bit and came up with this.

In the function "getSecretMessage" I changed to this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
string getSecretMessage(string str)
{
	std::cout << "Secret Message: ";
	if (str.length() > 0 && (str[0] != ' ' && str[1] != ' '))
	{std::cout << '"'; ((str.length() != 0) ? std::cout << str[0] : std::cout << "");}
	else
		std::cout << '"';

	for (int i = 0; i < str.length(); i++)
	{
		if (str.length() == 0) break;

		if (str[i] == ' ' && str[i + 1] == ' ') break;

		if (str[i] == ' ' && str[i + 1] != ' ')
		{
			std::cout << str[i + 1];
		}
	}
	std::cout << '"' << std::endl;

	return str;
}


I think this is what you are wanting.

Hope that helps,

Andy
Last edited on
Thank you, Andy!

I apologize for the format, this is actually the first time someone has told me how to format properly on this site :( Now I know for next time :)

Thanks again!



Hello donda97,

You are welcome.

If you have your answer put a green check on the subject line to let everyone that you are done.

Andy
Topic archived. No new replies allowed.