Reputation: 21
I'm trying to convert a sentence from upper case to lowercase. I also write a code but I stopper when a space is appear. How can I fix this problem and convert the whole sentence? Here is my code
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[100];
cin>>str;
for(int i=0;i<strlen(str);i++)
{
if(str[i]>='A'&&str[i]<='Z')
{
str[i]=str[i]+32;
}
}
cout<<str<<endl;
return 0;
}
Upvotes: 2
Views: 4312
Reputation: 89725
Here is one of the examples of doing it using transform function.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
if (getline(cin, str))
{
transform(str.begin(), str.end(), str.begin(), ptr_fun<int, int>(toupper));
}
cout << str << endl;
return 0;
}
Upvotes: 0
Reputation: 96845
The reason input stops at whitespace is because formatted input is delimited by whitespace characters (among others). You will need unformatted I/O in order to extract the entire string into str
. One way to do this is to use std::istream::getline
:
std::cin.getline(str, 100, '\n');
It's also useful to check if the input succeeded by using gcount
:
if (std::cin.getline(str, 100, '\n') && std::cin.gcount())
{
...
}
But in practice it's recommended that you use the standard string object std::string
which holds a dynamic buffer. To extract the entire input you use std::getline
:
std::string str;
if (std::getline(std::cin, str)
{
...
}
Upvotes: 0
Reputation: 3761
The error is because operator>>
delimites on spaces. The alternative is to use getline
. See the following example:
#include <cstring>
#include <iostream>
#include <string>
int main() {
std::string s;
std::getline(std::cin, s);
std::cout << "Original string: " << s << std::endl;
if (!std::cin.fail()) {
const int len = strlen(s.c_str());
for (size_t i = 0; len > i; ++i) {
if ((s[i] >= 'A') && (s[i] <= 'Z'))
s[i] = s[i] - 'A' + 'a';
}
}
std::cout << "New string: " << s << std::endl;
return 0;
}
Upvotes: 0
Reputation: 409404
It's because of theinput operator >>
, it breaks on space. If you want to read a whole line then use std::getline
to read into a std::string
instead.
Then read about the C++ standard algorithms, like for example std::transform
. Also, std::tolower
doesn't modify anything that's not an upper-case letter, so it's a good function to use.
Upvotes: 1