In your for loop for(int i=0; i<=s.length(); i++ "s.length()" or "s.size()", both return the same value will run the for loop the needed amount.
The "<=" is the problem as it will loop one more time than you want. If the length, or size, of the string is 10 the string elements are 0 - 9. 10 is past the end of the string.
Changing "<=" to just "<" should solve your problem.
Also the ".length()" and ".size()" functions return a number of type "size_t", so the for loop should be: for(size_t i = 0; i < s.length(); i++ to avoid any warnings that the compiler might generate.
Thank you for your response, but that's not what I meant. I want the program to loop the main function if the sentence introduced does not end with a fullstop.
Example,
Sentence is: My name is mermaidly (not accepted)
Sentence is: My name is mermaidly. (accepted)
The sentence will be converted into "MY NAME IS MERMAIDLY."
1 2 3 4 5
do {cout << "Sentence is: ";
getline(cin,s);
uppercase(s);
cout << s <<endl;}while(s!='.');
#include <cctype> // <--- std::tolower() and std::toupper().
#include <iostream>
#include <string> // <--- For using std::string and std::getline().
usingnamespace std;
void uppercase(string &s)
{
for (size_t i = 0; i < s.length(); i++)
{
s[i] = toupper(s[i]);
}
}
int main()
{
string s;
do
{
cout << "Sentence is: ";
getline(cin, s);
if (s[s.size() - 1] != '.')
{
std::cout << "\n Sentence must end with a period.\n\n";
}
} while (s[s.size() - 1] != '.');
uppercase(s);
cout << "\n Converted sentence is: "<< s << endl;
return 0; // <--- Not required, but makes a good break point.
}
Notice the addition of the header files that you need.
The parts in bold will get the last character in the string before comparing it to '.'.
This is based on the last character of the string being a period or not. If you need to do something with more than 1 period in a sentence you may need to go a different direction.