First of all i am new in programming. I was asked to create a program that prompts the user to insert a word and then I translate it into some sort of fake language. So i make the following:
firstLetter of the new word is the last char of the original word secondLetter is ncy thirdLetter is the entered word without the first and last char fourthLetter is nan fifthLetter is the first character of the word
e.g. user enters= dog new word is: gncyonand
My code is this but its failing and I assume is because the string does not exist yet(the user still has to insert it). Please help:
**
#include <iostream> //for cin and cout
#include <string> //for string data
using namespace std;
int main()
{
//I add a welcome message:
std::cout << "*************************************************\n"
<< " Welcome to Nacy-latin converter program\n"
<< "*************************************************\n\n";
// I declare first string:
std:: string userWord; //the word the user imputs
std::string firstLetter= userWord.substr(-1,0); //last char of the entered word
std::string secondLetter = "ncy";
std::string thirdLetter= userWord.substr(1, userWord.length() - 1); //last char of the entered word
std::string fourthLetter = "nan"; //just nan
std::string fifthLetter= userWord.substr(0,1); ; //the first char of the userWord
//I ask the user to imput data:
cout << "Hey there!";
cout << endl<<endl;
cout << "Please enter a word with at least two letters and I will converted into Nacy-latin for you:\n";
//return data to the user:
cout<<"The word in Nancy-Latin is:" <<firstLetter << secondLetter << thirdLetter <<fourthLetter <<fifthLetter<<'\n';
// Farewell message
cout << "\nThank you for the 'Nancy-latin' converter tool!\n";
// system(“pause”);
return (0) ;
}
**
Did you use Python before? std::string
does not allow negative indexes. You can use a mix of front()
, back()
, and substr()
string methods to get individual pieces and then use the C++ class std::stringstream
to build your new string.
std::stringstream ss;
ss << userWord.back() << "ncy";
ss << userWord.substr(1, userWord.size() - 2);
ss << "nan" << userWord.front();
std::cout << ss.str();
Do not forget to check user input for at least two characters.
Alternative to make new word in place.
std::swap(userWord.front(), userWord.back());
userWord.insert(1, "ncy");
userWord.insert(userWord.size() - 2, "nan");
std::cout << userWord;