So, I'm doing a program that is suppose to convert a sentence into pig latin. I figured I would make a function which would handle the individual words, then I'd work on breaking up the sentence into individual words. I keep getting the error that my String Subscript is out of range when I run the program and enter a word to be converted. Any suggestions?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

string convertToPig(string);

int main()
{	//get user input
	string word;
	cout << "Enter word to be translated\n";
	cin >> word;
	cout << "you entered: " << word <<"\n" <<"the translation is: ";
	cout << convertToPig(word);
	
	

	system ("PAUSE");
	return 0;
}
string convertToPig(string arbitrary)
	
{
	string newWord;
	int x = 0;
	//gets the length of the word and couts the entire word starting
	//at the second letter of the word.
	for (int i = 1; i < arbitrary.length(); i++)
	{
		newWord[x++] = arbitrary[i];
	}
	//after the for loop it attached the first letter along with "ay"
	newWord += arbitrary[0];
	newWord += "ay";
	return newWord;
}
#include <iostream>
#include <string>
using namespace std;

string convertToPig(string);

int main()
{	//get user input
	string word;
	cout << "Enter word to be translated\n";
	cin >> word;
	cout << "you entered: " << word <<"\n" <<"the translation is: ";
	cout << convertToPig(word);
	
	

	return 0;
}
string convertToPig(string arbitrary)
	
{
	string newWord;
	int x = 0;
	//gets the length of the word and couts the entire word starting
	//at the second letter of the word.
	for (int i = 1; i < arbitrary.length(); i++)
	{
		newWord[x++] = arbitrary[i];
	}
	//after the for loop it attached the first letter along with "ay"
	newWord += arbitrary[0];
	newWord += "ay";
	return newWord;
}

Compiled this code without a problem and it works fine with input "hello". I am using g++ (linux). But yes I would initialize the newWord variable to a value. e.g. "nothing"

Edited 4 Years Ago by Software guy: missed info

D'oh!

I got it! I still had newWord[x] so I just got rid of that.

Now I just need to be able to break a sentence up into individual words.
Also thanks for the help guys.

Edited 4 Years Ago by Snow_Fox: n/a

This article has been dead for over six months. Start a new discussion instead.