Every keyboard on a computer has its own important functions.
If any key suddenly malfunctions, it can cause significant inconvenience.
Today, let's say there's a person named Xiao Ming, and the Caps Lock key on his computer is broken.
So, all the English letters he types are in lowercase.
Xiao Ming wants to prove that learning to code every week is very useful.
He decides to write a program that can automatically convert sentences into the correct case format.
He decides to write a program that can automatically convert sentences into the correct case format.
P.S. This is just a hypothetical scenario for the exam question. In reality, you can use the Shift key to achieve the uppercase functionality instead of Caps Lock.
In such situations, it's probably best to get the computer fixed as soon as possible.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
Each line represents a separate piece of data, consisting only of lowercase letters, spaces, and punctuation marks such as ",", ".", "?", "!". Each line contains no more than 1000 characters. | For each input line, output one line where the first letter of each sentence is capitalized, and standalone "i" is capitalized as well. |
yo! i am so fat. macbook air so cool! me, too. battle! who am i? | Yo! I am so fat. Macbook air so cool! Me, too. Battle! Who am I? |
Thought Process
Set a boolean variable cap. If cap == true, it means the current letter should be uppercase, and then set cap to false. If encountering ",", ".", "?", or "!", set cap to true.
If encountering the character "i", check if it is preceded and followed by a space or a punctuation mark. It is important to first check the current character position to avoid memory access errors.
Sample Code-ZeroJudge A217: Caps Lock Disaster
#include <iostream>
#include <cctype>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
string str;
while (getline(cin, str))
{
bool cap = true;
string ans = "";
for (int i = 0; i<str.length(); i++)
{
if (isalpha(str[i]))
{
if (cap)
{
ans += toupper(str[i]);
cap = false;
}
else if (str[i] == 'i')
{
if (i == 0 && str[i+1] == ' ') ans += toupper(str[i]);
else if (i == int(str.length())-1 && str[i-1] == ' ') ans += toupper(str[i]);
else
{
if ((str[i+1] == ' ' || str[i+1] == '.' || str[i+1] == '?' || str[i+1] == '!' || str[i+1] == ',') && (str[i-1] == ' ' || str[i-1] == '.' || str[i-1] == '?' || str[i-1] == '!' || str[i-1] == ',')) ans += toupper(str[i]);
else ans += str[i];
}
}
else ans += str[i];
}
else ans += str[i];
if (str[i] == '.' || str[i] == '!' || str[i] == '?') cap = true;
}
cout << ans << "\n";
}
}
//ZeroJudge A217
//Dr. SeanXD