Here is my problem:
Write a program that reads in a text file and converts it to pig Latin. i.e. if the first letter is a consonant, move it to the end and add “ay” to the end, if it is a vowel add “way” to the end. Here’s an example: “end the war” becomes “endway hetay arway”.

Here is my code at the moment:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

bool isVowel(char ch);
string rotate(string pStr);
string pigLatinString(string pStr);


int main()
{
ifstream infile;
string newstr;
int length;
char achar;
string str; 
string str1;
string str2;
string str3;

infile.open("c:\\PigLatin.txt");

cout << "Enter a string: ";
getline(cin, str1);

cout << endl;
cout << "Pig Latin String Is: " << endl;
cout << endl;
while (!infile.eof())
{
infile.get(achar);

if (achar != ' ') 
{
str = str + achar;

}	
else 
{
cout << pigLatinString(str)<< " ";
str = "";
}
}
if (achar == '!')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "!";
}
if (achar == '?')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "?";
}
if (achar == '.')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << ".";
}

cout << endl;
str = "";
cout << endl;
return 0;
}

bool isVowel(char ch)
{
switch (ch)
{
case 'A': case 'E':
case 'I': case 'O':
case 'U': case 'Y':
case 'a': case 'e':
case 'i': case 'o':
case 'u': case 'y': return true;
default: return false;
}
}

string rotate(string pStr)
{
string::size_type len = pStr.length();

string rStr;

rStr = pStr.substr(1, len - 1) + pStr[0];

return rStr;
}

string pigLatinString(string pStr)
{
string::size_type len;

bool foundVowel;

string::size_type counter;

if (isVowel(pStr[0]))
pStr = pStr + "-way";
else
{
pStr = pStr + '-';
pStr = rotate(pStr);
len = pStr.length();
foundVowel = false;

for (counter = 1; counter < len - 1; counter++)
if (isVowel(pStr[0]))
{
foundVowel = true;
break;
}
else 
pStr = rotate(pStr);

if (!foundVowel)
pStr = pStr.substr(1,len) + "-way";
else
pStr = pStr + "ay";
}
return pStr;
}

My problem is im really blanking on how to read from the file and get my program to read it and output it in the command prompt. So if you can help me figure that out thanks!

Recommended Answers

All 15 Replies

There are a bunch of ways to read in a file, but the best way for this kind of thing is probably to use something like:

std::string word;
std::ifstream infile("myFilename.txt", std::ios::in);
while(infile.fail() != true){
    infile >> word;
    std::cout << pigLatinString(word) << ' ';
}

This would go through the entire file converting each word to Pig Latin and outputting it to the console.

Where would i input that snip it of code?

i put it as follows and i get 2 errors.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

bool isVowel(char ch);
string rotate(string pStr);
string pigLatinString(string pStr);


int main()
{
ifstream infile;
string newstr;
int length;
char achar;
string str; 
string str1;
string str2;
string str3;

infile.open("c:\\PigLatin.txt");

std::string word;
std::ifstream infile("myFilename.txt", std::ios::in);
while(infile.fail() != true){
    infile >> word;
    std::cout << pigLatinString(word) << ' ';
}

cout << "Enter a string: ";
getline(cin, str1);

cout << endl;
cout << "Pig Latin String Is: " << endl;
cout << endl;
while (!infile.eof())
{
infile.get(achar);

if (achar != ' ') 
{
str = str + achar;

}	
else 
{
cout << pigLatinString(str)<< " ";
str = "";
}
}
if (achar == '!')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "!";
}
if (achar == '?')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "?";
}
if (achar == '.')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << ".";
}

cout << endl;
str = "";
cout << endl;
return 0;
}

bool isVowel(char ch)
{
switch (ch)
{
case 'A': case 'E':
case 'I': case 'O':
case 'U': case 'Y':
case 'a': case 'e':
case 'i': case 'o':
case 'u': case 'y': return true;
default: return false;
}
}

string rotate(string pStr)
{
string::size_type len = pStr.length();

string rStr;

rStr = pStr.substr(1, len - 1) + pStr[0];

return rStr;
}

string pigLatinString(string pStr)
{
string::size_type len;

bool foundVowel;

string::size_type counter;

if (isVowel(pStr[0]))
pStr = pStr + "-way";
else
{
pStr = pStr + '-';
pStr = rotate(pStr);
len = pStr.length();
foundVowel = false;

for (counter = 1; counter < len - 1; counter++)
if (isVowel(pStr[0]))
{
foundVowel = true;
break;
}
else 
pStr = rotate(pStr);

if (!foundVowel)
pStr = pStr.substr(1,len) + "-way";
else
pStr = pStr + "ay";
}
return pStr;
}

Where would i input that snip it of code?
i put it as follows and i get 2 errors.

OK, what are the errors? Are they compilation errors or runt-time errors?

The code that I gave wasn't really the kind that you can just insert into your own (for one thing, there's no error check to see if the file exists or not, which you should always do). You are supposed to look at it as an example and use the same principles to make a version of your own that works with your current code.

well all i really need the code to do now is take the information from the file and transfer it i just dont know where and what i need to put in for that to happen, because i never learned files and how to read them.

... i never learned files and how to read them.

Really? It seems strange for a teacher to set a question that explicitly asks you to use something that you haven't been taught yet?

In any case, you have some of the right bits in your code to do the file reading, you just need to tidy them up a bit. There are probably thousands of places on the internet that you can find out how to read text files. You should first Google for "c++ read text file" or something like that. In those places you might find something close to what I said before. You can read more about the ifstream class here.

If the code that you have written already compiles OK, but doesn't run properly, it could be because of the file name that you're using; you should test if the file opened OK before you try and do anything with it. So, a slightly fuller example of reading words from a text file and printing them to the screen might be:

#include <iostream>
#include <fstream>
#include <string>

int main(){
    /* Get the filename from the user */
    std::string filename;
    std::cout << "Enter a filename: ";
    getline(std::cin, filename);

    /* Try and open the file */
    std::ifstream infile(filename.c_str(), std::ios::in);

    /* Check that the file was opened OK, quit if not */
    if(infile.is_open() == false){
        std::cerr << "Error: unable to open " << filename << " for input. Exiting." << std::endl;
        return 1;
    }
    
    /* Go through the whole file... */
    std::string word;
    while(infile.fail() != false){
        /* ... get a word ... */
        infile >> word;

        /* Print the word to the screen */
        std::cout << word << ' ';
    }

    /* Close the file */
    infile.close();
    
    /* Done! */
    return 0;
}

Alright so your code shows how the user opens a file, but for my problem i need there to be a preset folder that is already written to and that way my code can read the english words and output the piglatin.

OK, so can't you just create a text file (using notepad or whatever your favourite text editor is) and save it to the folder that the executable for your code is generated in? To read in the file, just hard-code filename to be the name of the file that you created.

i created a file in Visual studio and its known as PigLatin.txt and that is the file that has the english words in it. So i just need it to read that file and put it through my code to get my piglatin. Any suggestions. here is the part where i open my file i created but it i dont know how to get it to read the file:

int main()
{
ifstream infile;
string newstr;
int length;
char achar;
string str; 
string str1;
string str2;
string str3;
string pStr;
char ch;

infile.open("c:\\PigLatin.txt");

cout << endl;
cout << "Pig Latin String Is: " << endl;
cout << endl;
while (!infile.eof())
{
infile.get(achar);

if (achar != ' ') 
{
str = str + achar;

}	
else 
{
cout << pigLatinString(str)<< " ";
str = "";
}
}
if (achar == '!')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "!";
}
if (achar == '?')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "?";
}
if (achar == '.')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << ".";
}

cout << endl;
str = "";
cout << endl;
isVowel(ch);
rotate (pStr);
pigLatinString(pStr);
infile.close();


return 0;

Here is my txt file.

hello there my friend.

So, on line 14 you already opened the file. This is a good start (as long as the file is directly in the c-drive, since you have given the filename as "c:\PigLatin.txt". For now, I would move this file into the folder where Visual Studio creates the executable for this project. I don't use VS, so I have no idea where that actually is.

You should then immediately check if the file was successfully opened, with something like

if(infile.is_open() == false){
    std::cerr << "Error, unable to open file." << std::endl;
    return 1;
}

This will give you a nice error if the file can't be opened.

For this application, you just want to get at the file one word at a time, so you don't really need to build up the words using get() . You can use the stream extraction operator ( >> ) to do this for you automatically. This is what I was demonstrating on lines 20 - 28 of the code that I previously posted. In that case, the extracted words were just printed to the console, but you would want to use your pigLatinString() function first, so I guess something like:

std::string word;
while(infile.fail() == fasle){
    infile >> word;
    std::cout << pigLatinString(word) << ' ';
}

For the simple file that you posted this would be sufficient. Text files can get very complex though, so you could spend ages checking that all the things are a word, for example if the file said:
"I would like 10 bananas"
you would get a strange result. Or if there was jibberish in there, like
"Hello my name is £%&&£"

There are all kinds of possibilities, but best to get it working on a simple example first.

So i did all that and looked at it and moved stuff around but i get the error that it cant open the file so that a start. heres my code now for the opening of file:

infile.open("c:\\PigLatin.txt");

if(infile.is_open() == false)
{
    std::cerr << "Error, unable to open file." << std::endl;
    return 1;
}

std::string word;
while(infile.fail() == false)
{
    infile >> word;
    std::cout << pigLatinString(word) << ' ';
}

cout << endl;
cout << "Pig Latin String Is: " << endl;
cout << endl;
while (!infile.eof())
{
infile.get(achar);

if (achar != ' ') 
{
str = str + achar;

}	
else 
{
cout << pigLatinString(str)<< " ";
str = "";
}
}
if (achar == '!')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "!";
}
if (achar == '?')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << "?";
}
if (achar == '.')
{
length = static_cast<unsigned int>(str.length());
newstr = str.substr(0,(length-2));
cout << " " << pigLatinString(newstr) << ".";
}

cout << endl;
str = "";
cout << endl;
isVowel(ch);
rotate (pStr);
pigLatinString(pStr);
infile.close();


return 0;
}

here is the error message in the command prompt:

Error, unable to open file.
Press any key to continue . . .

It's still trying to open "c:\PigLatin.txt", is this where the file currently is? Otherwise you'll have to change the file name for the infile.open(...) statement. The bonus with having it in the same file as the executable is that you don't have to worry about the full path, so you should just be able to do something like infile.open("PigLatin.txt"); .

i fixed my file name cause i saved it in the C: drive, here is how i fix it:

infile.open("C:\201\PigLatin.txt");

but i get an error message as shown here:
1>c:\users\goncalvesa2\documents\visual studio 2010\projects\lab4problem1\lab4problem1\lab4problem1.cpp(24): warning C4129: 'P' : unrecognized character escape sequence

Also,i get this other error which never showed up before1>c:\users\goncalvesa2\documents\visual studio 2010\projects\lab4problem1\lab4problem1\lab4problem1.cpp(88): error C2447: '{' : missing function header (old-style formal list?)

And that is for the piece of code below:

{
switch (ch)
{
case 'A': case 'E':
case 'I': case 'O':
case 'U': case 'Y':
case 'a': case 'e':
case 'i': case 'o':
bool isVowel(char ch)
case 'u': case 'y': return true;
default: return false;
}
}

Backslash in a string literal begins an escape character. If you want a literal backslash, double them up:

infile.open("C:\\201\\PigLatin.txt");

Alternatively, you can use forward slashes. That works too:

infile.open("C:/201/PigLatin.txt");

missing function header (old-style formal list?)

This means the compiler thinks you're starting a function body. Usually it's related to mismatched braces, but it's hard to say for sure with the little bit of code you posted.

commented: Good tip about the forward slashes +6

>c:\users\goncalvesa2\documents\visual studio 2010\projects\lab4problem1\lab4problem1\lab4problem1.cpp(24): warning C4129: 'P' : unrecognized character escape sequence

It thinks that the "\P" part of "c:\201\PigLatin.txt" is a control sequence (other examples are things like '\n', '\t', '\r', etc.). You should probably have:

infile.open("c:\\201\\PigLatin.txt");

I don't know about the other error, a quick search for "Compiler Error C2447" gave something about C-style lists, which could mean that you have some orphaned curly braces somewhere. However, this seems like it is some other part of your code beyond the scope of this thread. If you're happy that you can read the file, then I would mark this thread as solved and start a new one with a name that refers to this new problem, you're more likely to get someone who knows about that kind of thing looking at it then :)

good call, thanks ravenous for all the help.

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.