Hey guys,
I'm at the losing end of a problem involving strings and char input.
Basically, I have a tree full of morse code and alphabet equivalents in struct morsetree that i will decode against.
so when i decode **** * *-** *-** --- *-- *** *-* *-** -**, i should get hello world.
however, by using the fin >> temptree.morse, i get helloworld.
it is not extracting the whitespace between words (which is actully 2 spaces)
any help greatly appreciated

struct morsetree;
struct temptree1, temptree2;

 while (!fin.eof() )
    {
      fin >> temptree1.morse;

        if (morsetree.find(temptree1, temptree2))
        {
          fout << tree2.alpha;
        }
    }

Recommended Answers

All 4 Replies

the >> operator will always discard whitespaces.
You could use getline(), which keeps whitespaces:

#include <iostream>
int main()
{
	std::string str;
	getline(cin,str);
	cout <<	str << endl;
	cin.get();
        return 0;
}

input : hello world! output: hello world! and in your case you could even use it to loose the horrible eof() line:

while (getline(fin, temptree1.morse))  //get a line until end of file
{
    //do stuff with temptree1.morse
}
// end of file

}

Of course, once you get the whole line, you'll want to parse it using a stringstream and getline() again...

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

char morse_decode( string letter )
  {
  ...
  }

bool is_multiple_spaces( char a, char b )
  {
  return (a == ' ') && (b == ' ');
  }

int main()
  {
  string line, letter, message;

  cout << "Please enter your message. Press ENTER twice to finish." << endl;

  while (getline( cin, line ))
    {
    if (line.empty()) break;
    stringstream letters( line );
    while (getline( letters, letter, ' ' ))
      if (letter.empty()) message += ' ';
      else message += morse_decode( letter );
    message += ' ';
    }

  // Remove extra spaces
  unique( message.begin(), message.end(), is_multiple_spaces );

  cout << "The decoded message is:\n"
       << message
       << endl;

  return 0;
  }

Hope this helps.

commented: Nice :) +5

Of course, once you get the whole line, you'll want to parse it using a stringstream and getline() again..
[..code...]

Ah, but now you're just showing off your coding skillz, because the OP never asked for that :P
It is nice code of course :)

:$ Actually, I was just trying to be helpful.

At least I didn't make any really dumb errors this time... :-O

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.