Loop to print string backwards - c++

Program asks user for a series of strings (their name and an 8 letter word), prints their name, the first and last three letters of the word, and then prints their word backwards. need help with the for loop to display string backwards.
#include <iostream>
int main () {
string FirstName;
string LastName;
string MiddleName;
string Names;
string string1;
int len;
int x;
cout << "Hello. What is your first name?" << endl;
cin >> FirstName;
cout << FirstName << ", what is your last name?" << endl;
cin >> LastName;
cout << "And your middle name?" << endl;
cin >> MiddleName;
Names = LastName + ", " + FirstName + ", " + MiddleName;
cout << Names << endl;
cout << "Please enter a word with 8 or more characters (no spaces): " << endl;
cin >> string1;
len = string1.length();
if (len < 8){
cout << "Error. Please enter a word with 8 or more characters and no spaces: " << endl;
cin >> string1;
}
else if (len >= 8){
cout << "The word you entered has " << string1.length() << " characters."<<endl;
cout << "The first three characters are " << string1.substr(0,3) << endl;
cout << "The last three characters are " <<string1.substr(string1.length()-3,3) << endl;
x = string1.length()-1;
for (x = string1.length()-1; x >=0; x--){
cout << "Your word backwards: " << string1[x];
}
}
return 0;
}

You were almost there:
cout << "Your word backwards: ";
for (x = string1.length()-1; x >=0; x--){
cout << string1[x];
}
This way the loop will print each character in string1 but in reverse order, and the text "Your word backwards: " only once.

If you want to be fancy:
copy(string1.rbegin(), string1.rend(), ostream_iterator<char>(cout));

Simple a way is to store a string in a temp array from backwards and then use this temp array to print reverse string.
For eg:- temp[j--]=str[i ++] ; in a loop.
But be careful before this , intialise size of array 'temp' to size of original array. in this case 'str' here.

This is probably not the answer to you question but I'd one one of these:
std::cout << "Your word backwards: "
<< std::string(string1.rbegin(), string1.rend()) << '\n';
*std::copy(string1.rbegin(), string1.rend(),
std::ostreambuf_iterator<char>(std::cout << "Your word backwards: "))++ = '\n';
std::reverse(string1.begin(), string1.end());
std::cout << "Your word backwards: " << string1 << '\n';

Related

Determine the longest word in a text input

How do I create a program where it reads in text from the user and then outputs the shortest and longest words and how many characters these words contain?
So far, I can only create a program that counts the number of words in the text.
int count_words {};
string word;
cout << "Type a text:" << endl;
while (cin >> word)
{
count_words++;
}
cout << "The text contains " << count_words << " words." << endl;
Can the loop be manipulated so that it determines the shortest and longest words?
Simply declare a couple of string variables, and then inside the while loop you can assign word to those variables when word.size() is larger/smaller than the size() of those variable, eg:
size_t count_words = 0;
string word, longest_word, shortest_word;
cout << "Type a text:" << endl;
while (cin >> word)
{
++count_words;
if (word.size() > longest_word.size())
longest_word = word;
if (shortest_word.empty() || word.size() < shortest_word.size())
shortest_word = word;
}
cout << "The text contains " << count_words << " word(s)." << endl;
if (count_words > 0) {
cout << "The shortest word is " << shortest_word << "." << endl;
cout << "It has " << shortest_word.size() << " character(s)." << endl;
cout << "The longest word is " << longest_word << "." << endl;
cout << "It has " << longest_word.size() << " character(s)." << endl;
}
Online Demo
Alternatively:
string word;
cout << "Type a text:" << endl;
if (cin >> word) {
size_t count_words = 1;
string longest_word = word, shortest_word = word;
while (cin >> word) {
++count_words;
if (word.size() > longest_word.size())
longest_word = word;
if (word.size() < shortest_word.size())
shortest_word = word;
}
cout << "The text contains " << count_words << " word(s)." << endl;
cout << "The shortest word is " << shortest_word << "." << endl;
cout << "It has " << shortest_word.size() << " character(s)." << endl;
cout << "The longest word is " << longest_word << "." << endl;
cout << "It has " << longest_word.size() << " character(s)." << endl;
}
else {
cout << "No text was entered." << endl;
}
Online Demo

How to only print the first word of a string in c++

How do I set this up to only read the first word the user enters IF they enter to much info?
I do not want to use an if-else statement demanding they enter new info because their info was to much.
I just want it to basically ignore everything after the first word and only print the first word entered. Is this even possible?
const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);
cout << " The word is: " << word << endl;
cout << endl;
UPDATE
It HAS to be a cstring. This is something I am working on for school. I am asking a series of questions and storing the answers as cstring in the first round. Then there is a second round where I store them as string.
try this:
const int SIZEB = 10;
char word[SIZEB];
cout << " Provide a word, up to 10 characters, no spaces. > " << endl;
cin.getline(word, SIZEB);
std::string input = word;
std::string firstWord = input.substr(0, input.find(" "));
cout << " The word is: " << firstWord << endl;
cout << endl;
You need to do:
#include <string>
std::string word;
std::cout << "Provide a word, up to 10 characters, no spaces.";
std::cin >> word;
std::cout << "The word is: " << word;
If you have to have it less than 10 characters, you can truncate the string as necessary. No reason for C-style strings, arrays etc.
"I have to use a c string." Sigh...
char word[11] = {0}; // keep an extra byte for null termination
cin.getline(word, sizeof(word) - 1);
for(auto& c : word)
{
// replace spaces will null
if(c == ' ')
c = 0;
}
cout << "The word is: " << word << endl;
you could also use this method :
std::string str;
std::cin >> str;
std::string word;
int str_size = str.size();
for(int i = 0; i < str_size; i++){
word.push_back(str[i]);
if(str[i] == ' ') break;
}
std::cout << "\n" << word << std::endl;

Beginner C++ input behviour

This program is a very simple code in my practice to learn C++. The problem is at some point it does not accept input from cin and behaves strangely.
The code and the output of the program are below.
Why does the program not consider cin at "Enter your first name please"?
# include "cmath"
# include <iostream>
using namespace std;
int main()
{
string FirstName, MiddleName, LastName;
string WelcomeMessage = "Welcome to Visual C++";
int Number_of_Steps = 5;
int LoopStart = 1, LoopEnd = 5;
int AgeYears, AgeMonths;
double Pi = 3.14;
float k = 5.366;
double Age;
char* Symbol = "k";
bool TestResult = true;
MiddleName = "Milton";
cout << "Input Your First Name and Last Name" << endl;
cin >> FirstName >> LastName;
cout << "Input your Age in Years" << endl;
cin >> AgeYears;
cout << "Imput your Age in Months " << endl;
cin >> AgeMonths;
Age = AgeYears + AgeMonths / 12;
cout << endl << "Your Name is " << FirstName << ' ' << LastName << endl;
cout << "Your Age is " << Age << endl;
cout << "The Character is " << Symbol << endl;
// Testing operators
cout << "Please Enter a floating point number \n";
int n;
cin >> n;
cout << "n==" << n
<< "\n n+1==" << n + 1
<< "\n n three times==" << 3 * n
<< "\n n twice ==" << n + n
<< "\n nsquared ==" << n*n
<< "\n half of n ==" << n / 2
<< "\n square root of n ==" << sqrt(n)
<< "\n";
// Testing string addition
cout << "Eneter your first name please" << endl;
string String1, String2, String3;
cin >> String1;
cout << "Enter your family name please" << endl;
cin >> String2;
String3 = String1 + " " + String2;
cout << "Welcome" << " " << String3 << endl;
// testing inequalities to strings
string FirstString, SecondString;
cout << "Input First String "
<< endl;
cin >> FirstString;
cout << "Input Second String "
<< endl;
cin >> SecondString;
if (FirstString == SecondString)
cout << "The two words are identical \n";
if (FirstString >= SecondString)
cout << "First word is bigger than second word \n";
if (FirstString <= SecondString)
cout << "Second word is bigger than first word \n";
}
You get a hint from the output displaying .2 as the first name (String1). The cin operation before asking for first name had 64.2 on the buffer but because you read the value into an int n it only read the integer portion 64 and left the .2 on the buffer. Changing the declaration n to float n or doing some input validation if you did want an integer should leave the buffer empty when you get to the request for first name.

using get line in c++

Okay, I am trying to use the code:
getline(cin, phrase);
When I compile I get the error:
no matching function for call to 'getline'
Here is the full code:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
cout << "Challenge 1\n" << "Kaitlin Stevers\n" << "Characters and Strings" << endl;
cout << endl;
cout << endl;
char letter[2];
cout << "Please enter a letter: " << endl;
cin >> letter;
cout << "You entered: " << letter << endl;
char word[5];
cout << "Please enter a word up to 5 characters long: " << endl;
cin >> word;
cout << "The word you entered is: " << word << endl;
char phrase[100];
cout << "Please enter a phrase up to 99 characters long: " << endl;
getline(cin, phrase);
cout << "The phrase you entered is: " << phrase << endl;
string lettero;
cout << "Enter one letter: " << endl;
cin >> lettero;
cout << "The letter you entered is: " << lettero << endl;
string wordo;
cout << "Please enter a word: " << endl;
cin >> wordo;
cout << "The word you entered is: " << wordo << endl;
string phraseo;
cout << "Please enter five words: " << endl;
getline(cin, phraseo);
cout << "The words you entered are: " << phraseo << endl;
return 0;
}
'no matching function call for getline', cause getline takes a string not a char[] as argument. See cin.getline() if you absolutely want to pass a cha[] as argument.
As you see here.
This getline(cin, string) function accepts a string.
Although, there is also an instruction you can use to put the line into a char array like so:
char phrase[99];
cin.getline (phrase,99);
Or you could also get the input into a string, then convert it to a char array :
string temp = "";
cin >> temp;
char phrase[99];
strcpy(phrase, temp.c_str());

Seemingly simple issue with calling information from an array in C++

This seems like it should be easy, which is why it is driving me especially insane. Hopefully someone out there will see the problem right off. I'm just trying to build arrays from an array built from a user input. It seems to create an array that is bigger than the one I meant for it to. Here's the program:
int main()
{
ifstream inFile;
ofstream outFile;
int numReq, fileSize;
string lang, dash;
char fileName[40];
char confirm[10];
char confirm2[10];
int character;
char year[3];
char month[1];
char day[1];
char hour[1];
cout << "What file to process?" << endl;
cin >> fileName;
year[0] = fileName[14];
year[1] = fileName[15];
year[2] = fileName[16];
year[3] = fileName[17];
cout << "year = " << year << "." << endl;
month[0] = fileName[18];
month[1] = fileName[19];
cout << "month = " << month << "." << endl;
cout << "so I gotta know, what is..." << endl;
cout << "month[0]? " << month[0] << endl;
cout << "month[1]? " << month[1] << endl;
cout << "month[2]? " << month[2] << endl;
cout << "month[3]? " << month[3] << endl;
cout << "month[4]? " << month[4] << endl;
cout << "month[5]? " << month[5] << endl;
cout << "month[6]? " << month[6] << endl;
day[0] = fileName[20];
day[1] = fileName[21];
cout << "day = " << day << "." << endl;
hour[0] = fileName[23];
hour[1] = fileName[24];
cout << "hour = " << hour << "." << endl;
cout << "so, 'fileName[23]' is = " << fileName[23] << "?" << endl;
cin >> confirm;
cout << "So, the year is " << year << ", the month is " << month
<< ", the day is " << day << ", the hour is " << hour << "?" << endl;
cin >> confirm;
//cout << "Is this what you chose? " << fileName << endl;
//cin >> confirm;
//cout << "Which character to manipulate?" << endl;
//cin >> character;
//cout << "This one? " << fileName[character] << endl;
//cin >> confirm2;
inFile.open(fileName);
assert (!inFile.fail());
outFile.open("revisedPracticeFile1.txt");
outFile << fixed << showpoint; // I have no idea what this is...
outFile << setprecision(2); // .. or this for that matter.
cout << "Processing data" << endl;
inFile >> lang;
while (!inFile.eof() ){
if (lang.length() <= 2){
outFile << lang << " ";
// I should keep in mind, that, for whatever reason, it seemed like the
//item 'setw(6)' made the program work when I put it in, but didn't seem
//to make the program stop working when I took it out. Curious..
inFile >> dash >> numReq >> fileSize;
outFile << numReq << " " << fileSize << endl;
}
else{
inFile >> dash >> numReq >> fileSize;
cout << "took out " << lang << " " << numReq << " " << fileSize << endl;
}
inFile >> lang;
}
inFile.close();
//assert(!inFile.fail());
outFile.close();
return 0;
}
...And, this is what happens when I run the program:
What file to process?
projectcounts-20090101-010000
year = 2009.
month = 01009.
so I gotta know, what is...
month[0]? 0
month[1]? 1
month[2]? 0
month[3]? 0
month[4]? 9
month[5]?
month[6]?
day = 011009.
hour = 0111009.
so, 'fileName[23]' is = 0?
yes
So, the year is 1009, the month is 11009, the day is 111009, the hour is 0111009?
^C
... So what gives?
The syntax char year[3]; declares an array with 3 element. But, then you use it to store 4 elements. There are similar issues with your other arrays.
Also, you're using char arrays as strings. That's a C (not C++) way to do things. Of course you're allowed to do this if you want. But, these c-style strings use the convention that the last item is a zero.
Thus, if you wanted a C-style string to store the work 'foo', you could do it like this
char string[10]; // anything bigger than 3 works
string[0] = 'f';
string[1] = 'o';
string[2] = 'o';
string[3] = '\0'; // this zero tells functions like `printf` that the string has ended.
Without that last zero, functions like printf will just keep outputting memory locations until it happens upon a zero somewhere.
EDIT: Consider using c++ std::string for your string processing.