Question

I keep running into an issue with this code in C++:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

int main ()
{
   string words[25];
   int i = 0;
   char * word;
   cout << "Input a phrase, no capital letters please.";
   char phrase[100] = "this is a phrase";
   word = strtok (phrase, " ,.");

   while (word != NULL)
   {
      i++;
      words[i] = word;
      cout << words[i] << " ";
      word = strtok (NULL, " ,.-");
      int g = 0;
   }
   cout << endl << endl;

   int g = 0;
   while (g < i)
   {
      g++;
      char f = words[g].at(0);
      if ((f == 'a') || (f == 'e') || (f == 'i') || (f == 'o') || (f == 'u') || (f == 'y'))
      {
         words[g].append("way");
         cout << words[g] << " ";
      }
      else
      {
         words[g].erase (0,1);
         cout << words[g] << f << "ay" << " ";
      }

   }
   cout << endl;
   system("PAUSE");
}

I actually want my program user to generate the phrase to be put in char phrase[100] but I can't figure out the proper syntax to initiate input on it without screwing up the translation.

This is a program that translates phrases into pig latin BTW.

Was it helpful?

Solution

What you want is:

char phrase[100];
fgets(phrase, 100, stdin);

Though, as stated in the comments and other answer, you're using C string functions in C++ and this is very odd. You should not do so unless you are required by an assignment or something.

Instead use:

string input;
getline(cin, input);

To tokenize you can do the following:

string token;
size_t spacePos;
...
while(input.size() != 0)
{
    spacePos = input.find(" ");
    if(spacePos != npos)
    {
        token = input.substr(0, spacePos );
        input = input.substr(spacePos  + 1);
    }
    else
    {
        token = input;
        input = "";
    }

    // do token stuff
}

Or, to skip all of that jazz:

string token;

while(cin >> token)
{
    // Do stuff to token
    // User exits by pressing ctrl + d, or you add something to break (like if(token == "quit") or if(token == "."))
}

OTHER TIPS

The preferred way of doing terminal I/O in C++ are streams. Use std::cin and the std::getline function to read strings from input output.

std::string input;
std::getline(std::cin, input);

After that you probably want to get rid of strtok and look at this question to understand how to do string tokenization in C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top