So I am trying to write to a file I/O in C++ where the user wants to translate a different language, an example would be morse code to english. I using the function morseToEnglish() and passing it in as a token for my output file. The issue I am having with this is that I am getting the correct output, but I am missing a newline somewhere.
Here is what I have so far:
char morsing[256]; //reading line by line
if (inputfile.is_open())
{
while (inputfile.getline(morsing, 256)) // reading character by character
{
token = strtok(morsing, "|"); //break each word into token
cout << "Read the input file: " << "morsingMC.mc" << endl;
while (token != NULL)
{
**outputfile << morseToEnglish(morsing); **
token = strtok(NULL, "|");
}
}
}
If I am doing
outputfile << morseToEnglish(morsing);
this will be the output:
123 456 789123 456 789123 456 789123 456 789123 456 789
instead of:
123 456 789
123 456 789
123 456 789
123 456 789
123 456 789
I have also tried using the endl and "\n" with my outputfile but this will output each word into token instead. This is a minor change but how can I modify my newline so that my output will go to a newline without breaking the token?
Edit: morseToEnglish() is a function that converts morse code into English which is in the header file and inputfile/outputfile are ifstream/ofstream respectively
Okay, let's start with a really simple bit of advice: when you're writing C++, forget that you ever even heard of
strtok. Just don't use it--ever.While you're at it, it's probably just as well to forget about the existence of
std::istream::getlineas well. If you want to read a line of data, your first choice should usually bestd::getlineinstead. That works with anstd::string--which should usually be your first choice for how to store/represent/manipulate strings.Yes, there are exceptions to all of that, but they're reasonable starting points until/unless you have some specific reason to do otherwise.
Getting to the question, I surmise you have some input like:
So, for example, if a line of input contained the classic "SOS", it would be something like:
Seem at least sort of close to reality so far?
I'm also guessing that what you're hoping to achieve is read in a line, translate each token on that line into English, print out the tokens, print a new-line, and then proceed to the next, and repeat until the end of the file.
Assuming that's the case, I'd write the code something like this:
Then
processwill process one line of input, something like this:That is guessing about what you want, but if I'm reading things right, it seems to fit at least reasonably closely.