Andrea B.
Andrea B.

Reputation: 113

C++ Pig Latin is not working

So, I have tried and tried to make this c++ pig latin program, but it's just not working. Here is my code:

int main()
{
string tmp = "";
char a;

cout << "String: "; getline(cin, tmp);

char pigLatin[1024];
strncpy(pigLatin, tmp.c_str(), sizeof(pigLatin));
pigLatin[sizeof(pigLatin) - 1] = 0;

a = pigLatin[0];
pigLatin[sizeof(pigLatin)] = '-';
pigLatin[sizeof(pigLatin) + 1] = a;
pigLatin[sizeof(pigLatin) + 2] = 'a';
pigLatin[sizeof(pigLatin) + 3] = 'y';

for (int i = 1; i < sizeof(pigLatin); i++)
{
    cout << pigLatin[i];
}
cout << endl;
system("PAUSE");

return 0;
}

When I run it, it doesn't return any runtime errors or anything, but when I enter a string it just puts the string minus the first letter and then a bunch of spaces. Does anyone know the problem?

Upvotes: 0

Views: 96

Answers (1)

Captain Obvlious
Captain Obvlious

Reputation: 20063

The problem is that sizeof returns the size in bytes of the array not the length of the string it contains. In this case the result of sizeof is 1024 assuming char is 8 bits. You could always use strlen to determine the length of the string or you can eliminate the use of a naked array altogether and use std::string instead. This would decrease the size of your code significantly. Something like this...

int main()
{
    cout << "String: " << flush;
    string pigLatin;
    getline(cin, pigLatin);

    pigLatin += '-';
    pigLatin += pigLatin[0];
    pigLatin += "ay";
    pigLatin.erase(0, 1);

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

Upvotes: 2

Related Questions