1

I am busy with a practical. I have to enter a string or a message and have to convert it to Morse code: 'A' = .- 'B' = -... ecs.

I can do that with no problem by using a series of if statements.

for(int i = 0;i < stringvalue.length();i++)
{
    if(stringvalue == 'A')
        cout << ".-";
        //there is 26 if statements

}

But when i enter a string, eg.

"Testing data"

Only the first part of the string is converted(test is converted) to Morse.

Why does it not convert the part after the space. If there is a space in the string it must output "/ ".

2
  • Using cin >> will break at the space. Look at using getline instead: en.cppreference.com/w/cpp/string/basic_string/getline Commented Aug 6, 2012 at 9:28
  • Also, instead of using 26 ifs, maybe you could use a table (array) of Morse code values, and look up each letter in the table. Commented Aug 6, 2012 at 9:35

2 Answers 2

3

If your input routine looks like this:

std::string input;
std::cin >> input;

The input is read up to the first whitespace character. To read the whole line, you can use std::getline.

std::getline(std::cin, input);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that helped. I will accept your answer in 10 minutes;
2

Because you're reading the string from stdin using cin >> stringvalue. The C++ operator>>(istream, string) stops after whitespace; it reads only a single space-separated token at a time.

Instead, use getline:

std::getline(std::cin, stringvalue);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.