Hey guys i need help with this code. I don\'t understand why is not stopping the
ID: 3762434 • Letter: H
Question
Hey guys i need help with this code. I don't understand why is not stopping the capitals after the If statement. The problem is:::::Write a program that capitalizes every other word in an input sentence until punctuation is reached. After the punctuation, the rest of the sentence should be as is in the input sentence. This is the code I have right now but the after punctuation If loop is not working. And please guys explain to me the problem i want to understand so later on in the future I wont have this issue:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
int i=0;
int j=0;
int k=-1;
cout<< "Type a sentece: ";
getline (cin, s);
for (i=0; i<=s.length(); i++){
for (j=k+1; isspace(s.at(j))==false; j++){
if(ispunct(s[j]))
break;
else
cout<< s[j];
}
cout<<' ';
for (k=j+1; isspace(s.at(k))==false; k++){
if(ispunct(s[k]))
break;
else
s[k] = toupper(s.at(k));
cout<< s[k];
}
if(ispunct(s[i]))
break;
else
cout<<' ';
}
return 0;
}
Explanation / Answer
you need to put an extra condition in for loop that index should be less than string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
int i=0;
int j=0;
int k=-1;
cout<< "Type a sentece: ";
getline (cin, s);
for (i=0; i<=s.length(); i++){
for (j=k+1; j< s.length() && isspace(s.at(j))==false; j++){
if(ispunct(s[j]))
break;
else
cout<< s[j];
}
cout<<' ';
for (k=j+1; k < s.length() && isspace(s.at(k))==false; k++){
if(ispunct(s[k]))
break;
else
s[k] = toupper(s.at(k));
cout<< s[k];
}
if(ispunct(s[i]))
break;
else
cout<<' ';
}
return 0;
}