Transformation to lower case in C++ - c++

#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include <string>
#include <algorithm>
using namespace std;
string A,B;
int main()
{
int t,l,i;
scanf("%d",&t);
while(t--)
{
std::string str;
std::getline(cin, str);
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
cout<<str;
/*for(i=0;i<s.length();i++)
{
s[i]=toupper(s[i]);
}*/
}
return 0;
}
i wrote this code to convert to lower case but when run on ideone with input
1
hola please!!!
it shows output no can u tell or correct it morever this will help me learn the use of std:lowercase function taking getline cin as input rather than considering it as array

The problem is definitely with the way you are reading in. scanf("%d",&t); doesn't consume the return character, so it is still there on the getline, which will get an empty sting. Change it to scanf("%d\r",&t).

If you simplify the code, the problem can be reduced to:
int main() {
int t;
scanf("%d",&t);
std::string str;
std::getline(cin, str);
std::cout<<str;
}
This is because scanf reads from the input until it reaches a character that doesn't match, and it leaves that character in the input buffer. You input is "1\nhola please!\n\0", so scanf reads the 1, and leaves the rest: "\nhola please!\n\0". Then, you tell it to read until the next \n is found, which is immediately, so it returns an empty string.
The solution is: after using std::cin >> or scanf or whatever, if the next thing you want to do is read the rest of the line, you want to ignore that leading newline character. The C++ way to do this is std::cin.ignore(0xFFFFFFFF,'\n');, which will ignore the rest of the line. Alternatively, use scanf("%d\n" &t); to get the scanf to read in the newline character.
Related, you never check the validity of any of your input:
int main() {
int num_lines=0; //variables on different lines and initialized
std::cin >> num_lines
if (!std::cin)
return 1;
std::string str;
for(int j=0; j<num_lines && std::getline(sd::cin, str); ++j) {
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::cout << str;
}
return 0;
}

Or simply use < boost/algorithm/string.hpp > header and function boost::to_lower().
int t = 0;
scanf("%d",&t);
std::cin.ignore();
while(t--) {
std::string str;
std::getline(cin, str);
boost::to_lower(str);
std::cout << str << std::endl;
}

Related

Output Befor giving the input of string for finding palindrome

This code is giving output YES just after entering the value of test case.
Code: for alphanumeric pallindrome
int main() {
int t;
cin>>t;
while(t--){
string s;
int count = 0,size = 0;
getline(cin,s);
cout<<s<<endl;
s.erase(remove_if(s.begin(),s.end(),not1(ptr_fun((int(*)(int))isalnum))), s.end());
for(int i=0;i<=s.size()/2;i++){
size++;
if(tolower(s[i])==tolower(s[s.size()-i-1])){
count++;
}
else
break;
}
if (count==size)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
Output I am getting is YES without giving any input of string
For Input:
2
I am :IronnorI Ma, i
Ab?/Ba
Your Output is:
YES
I am :IronnorI Ma, i
YES
This code is giving output YES just after entering the value of test
case. Output I am getting is YES without giving any input of string
Your problem is here:
/* code */
cin>>t; -----------> std::cin
while(t--)
{
string s;
int count = 0,size = 0;
getline(cin,s); ------------> std::getline()
/* remaining code */
Reading with something like std::cin leaves the newline in the input stream. When the flow of control reaches std::getline(), the newline will be discarded, but the input will cease immediately. This leads, std::getline()s attempt read a new line and skips the input.
FIX: When switching from white space delimited to newline delimited input, you want to clean all newlines from the input stream by doing a std::cin.ignore()
The fixed code should be: https://www.ideone.com/ucDa7i#stdin
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
// fix
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(t--)
{
std::string s;
int count = 0,size = 0;
getline(std::cin,s);
/* remaining code */
}

Stringstream parse comma-separated integers

So guys, Actually What I wanna do here is that when I input 3,12,36 the output will be:
3
12
36
But here I have difficulty on how to make it output all the answer. What I have been doing is that when you input 3,12,36 it will output 3 12 only and if you type 3,12,36,48 it will output 3 12 36.
So it will always miss the last integer because my while loop is not correct I guess. but if I change it into
while(output >> life|| output >> ch)
It doesn't work either. I've done a lot of research but it still makes me confused and I'm still stuck on this part.
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life >> ch){
lifeishard.push_back(life);
//lifeishard.push_back(life2);
//lifeishard.push_back(life3);
}
return lifeishard;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
On your last number, the while loop fails because there's no character at the end. Just the end of the string. So it doesn't execute the push_back inside the loop.
Change it so that the while loop just gets the number. Then do the push_back in the loop. Then in the loop, after the push, get the comma character. Don't bother checking for failure getting the comma because when it goes around the while loop again it will fail and exit.
I changed to using getline in your main. I changed your loop index to size_t because it is never a good idea to mix signed and unsigned integers, and whenever you use a size() function, it's a size_t. When posting your program it really should include everything. My fixed up version of your program:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life){
lifeishard.push_back(life);
output >> ch;
}
return lifeishard;
}
int main() {
string str;
getline(cin, str);
vector<int> integers = parseInts(str);
for(size_t i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
// Here is how we do for loops over containers in modern C++
for(auto x: integers) {
cout << x << '\n';
}
return 0;
}
A combination of stringstream, getline with delimiter and stoi would be enough for the conversion:
From the C++ reference for getline with delimiter:
Extracts characters from is and stores them into str until the delimitation character delim is found.
With this in mind, the code example below assumes the input is well-formed:
Example
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> parseInts(const string& str, const char delim = ',')
{
vector<int> parsed;
stringstream ss(str);
string s;
while (getline(ss, s, delim)) // <- stores input in s upon hitting delimiter
parsed.push_back(stoi(s)); // <-- convert string to int and add it to parsed
return parsed;
}
int main()
{
string str = "3,12,36"; // <-- change to cin if you'd like
vector<int> ints = parseInts(str);
for (auto& i : ints)
cout << i << "\n";
}
Output
3
12
36
See more: getline, stoi

terminate while loop using character

I need help with the following snippet:
Using string in the following loop terminates:
int main() {
string in;
while(1){
cin >> in;
if (in == "|")
break;
}
But using int in the following loop does not terminates:
int main() {
int in;
while(1){
cin >> in;
if (in == '|')
break;
else
cout<< in << "\n";
}
I want to terminate the last shown snippet. Is it possible to do using int in.
I've seen the post C++ Terminate loop using a char input to int but no solution.
While characters are represented in the computer as small integers, an int is not the same as a char. Not in C++.
When you read into an int variable the >> operator tries to parse the input as an integer, as a number and not as a character.
If you want to read a character then read a character:
char in;
std::cin >> in;
If you try to read an integer, and the input is not a number, then the input operator will fail. See e.g. this very simple example.
This is the approach I used
I needed to input integers to a vector as input using while loop indefinitely and terminate it using a character.
This approach takes the input as character and then convert this char into integer.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
char in;
std::vector<int> vec;
while(1){
cin>>in;
if(in == '|'){
break;
}
vec.push_back(in - '0');
}
for(int j=0; j<vec.size(); j++){
cout<<vec[j];}
return 0;
}

Taking input of strings with white spaces

I am trying to input strings which may contain white spaces.The entire string can be made of white spaces.
Here is what I am doing-
#include <bits/stdc++.h>
using namespace std;
char arr[1000][1000];
int main()
{
int t,m=3,n=2;
cin >> t;
while(t--)
{
string str;
for(int i=0;i<m;i++)
{
getline(cin,str);
cout << str[0] << endl;
}
return 0;
}
}
Here t is no of test cases.
Say for m=3, I have this input-
1
#T
--
--
For visibility, - is used to represent white spaces.In actual input,there are white spaces instead of - .
This is the output I get-
NUL
#
-
Another thing which I tried is this-
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
cin >> arr[i][j];
}
where m=3,n=2 for the example above.But printing this arr gives me following output-
#T
NULNUL
NULNUL
I am not sure why I am getting this output.Why am I getting NUL instead of white spaces.Also in the first code, the output I get is NUL before # ,why is that?
There's no need to write such a complicated code to obtain whitespaces from cin. You can just take an advantage of std::noskipws flag.
Solution 1:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char x;
for (int i=0; i<10; i++)
{
cin >> noskipws >> x;
str += x;
}
cout << str;
}
Live demo
Solution 2:
or even simpler, without any string:
#include <iostream>
using namespace std;
int main()
{
char str[10];
cin.read(str, sizeof(str));
cout << str;
}
Live demo
Solution 3:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
cout << str;
}
Live demo
You are printing str[0] - this is not a string, this is a single character. When your string is empty, the only thing it contains is null-terminator ('\0'). And when you access the first element of your string with [], you are accessing this null-terminator. And since you are printing it as a character, you see NUL as your output.

String length getting reduced by using getline?

I am using getline and ignore but something is not working properly,
Below is the sample code which am not able to understand how it is working.
int main()
{
string str;
int t,length;
cin>>t; // t is the number of test cases
while(t--!=0)
{
cin.ignore();
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
Sample output:
2
hey hi
length 6
hey hi
length 5
Why is the length decreasing? Is this because of getline and ignore function? Any help would be appreciated.
The reason it is giving a different length is becaus your ignore() function ignores only one character. The first time round it ignores the return key you pressed after entering the number. But std::getline() deletes the return character for you. So the second time round ignore() deletes the first letter of your string making it "eh hi".
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// first removed RETURN character after removes first letter
cin.ignore();
getline(cin, str);
length = str.size();
cout << "length = " << length;
}
}
Try using this instead:
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
while(t-- != 0)
{
// cin.ignore(); // dont do this here please
// cin >> ws skips all whitespace characters
// including the return character
getline(cin >> ws, str);
length = str.size();
cout << " length = " << length;
}
}
Alternatively (maybe better) you can move the ignore() function out of the loop to where t is really needed:
#include <limits>
int main()
{
string str;
int t, length;
cin >> t; // does not remove the RETURN character
// ignore as many characters as necessary including the return
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while(t-- != 0)
{
// cin.ignore(); // not here
getline(cin, str);
length = str.size();
cout << " length = " << length;
}
}
The cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); looks complicated but it is the only way to guarantee that any spurious characters (like spaces) are removed. You can probably get away with just cin.ignore() for the exercise if you want.
Read up on std::istream::ignore()
cin.ignore() defaults to ignoring one character.
If you output your string each time, you'll see that in later cases the string is equal to "ey hi". The h is being dropped.
The value of the string held by cin drops its first character before being passed to getline.
Since you're using getline, you can simply remove the cin.ignore() from your loop and your program should work as intended.
However, you should also change your cin>>t; line. In this case, the ignore() is dropping the line return after the input value 2. A stringstream here allows for a getline(...) function, or alternatively you can use cin.ignore(str.max_size(), '\n');.
In the case of the stringstream, your code would become:
#include <sstream> // stringstream
#include <string> // std::string
#include <iostream> // cin
int main()
{
string str;
int t,length;
getline(cin, str);
std::stringstream stream;
stream << str;
if (!(stream >> t)) {
// Couldn't process to int
}
// cin>>t; // t is the number of test cases
// No longer need this line.
while(t--!=0)
{
// cin.ignore(); Drop this too
getline(cin,str);
length=str.size();
cout<<"length="<<length;
}
}
If you are not interested in whitespace,
then use getline(cin >> ws, str)