reverse string program is not working correctly - c++

I tried writing a string reversing program in C++. Though it seemed really simple, Idk why I ain't getting the correct output.
Here's my code:-
#include<iostream>
#include<string>
using namespace std;
string Reverse_string( string &s ){
for( size_t i{}; i<s.size() ; i++ ){
s.at(i)= s.at( s.size()-1-i );
}
return s;
}
int main(){
cout<<"Enter the string you want to reverse: ";
string s{};
getline(cin,s);
cout<<"\nThe reversed string is :"<< Reverse_string(s) << endl;
return 0;
}
Here is my output:-
Enter the string you want to reverse: string
The reversed string is :gniing
Please help me finding the bug!

In your code you are assigning the values s.at(i)= s.at( s.size()-1-i ); and thus it is changing the previous value of s.at(i), but you should swap the values of respective indexes, s.at(i) with s.at(s.size()-1-i). And also you only need to traverse the first half of the string to swap with respective last half of the string.
This works fine.
#include<iostream>
#include<string>
using namespace std;
string Reverse_string( string &s ){
for( size_t i{}; i<s.size()/2 ; i++ ){ // here you only need to go half
swap(s.at(i), s.at( s.size()-1-i )); // swap is builtin function
}
return s;
}
int main(){
cout<<"Enter the string you want to reverse: ";
string s{};
getline(cin,s);
cout<<"\nThe reversed string is :"<< Reverse_string(s) << endl;
return 0;
}

Instead of using functions. You can just use the headerfile #include <algorithm>. There is a built in reverse function.
#include <iostream>
#include <algorithm>
int main()
{
std::string s;
std::cout << "Enter the string you want to reverse: ";
std::cin >> s;
std::reverse(s.begin(), s.end());
std::cout << "The reversed string is: " << s;
return 0;
}

Related

Convert char array to a string with cin.getline(.)

hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}

How do you remove multiple characters in the strings that are held in a vector, in c++?

I want to delete characters of a string that are in a vector, starting from an index inputted by the user up until the end of that string. For example if in index 0, my vector has the string "hello" and index 1 has the string, "goodbye", I want to erase the characters "llo" in the first string and "dbye" in the second string. So the result will be "he" in index 0 and "goo" in index 1. In my code that I am posting, I did not add the part of getting input from the user for the index. But just pretend, it is index 4 and beyond. How would I do this? Thank you.
I tried putting a '\0' character at the index that I want to start the deletion at, but that does not work.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int maxSize;
cin >> maxSize;
string usrInput;
vector<string> myArray;
for(int i = 0; i < maxSize; i++)
{
cin >> usrInput;
myArray.push_back(usrInput);
}
myArray[0][4] = '\0';
cout << myArray[0];
return 0;
}
You can combine the std::string method substr with the standard algorithm std::for_each to apply your cutting function to all strings in the vector.
#include <algorithm> // std::for_each
std::cout << "cut at length: ";
if(size_t cutpoint; std::cin >> cutpoint) {
std::for_each(myArray.begin(), myArray.end(), [&cutpoint](std::string& str) {
str = str.substr(0, cutpoint);
});
}
the std::string class provides a method substr which do the job.
Example:
int main()
{
int maxSize;
cin >> maxSize;
string usrInput;
vector<string> myArray;
for(int i = 0; i < maxSize; i++)
{
cin >> usrInput;
myArray.push_back(usrInput);
}
for ( auto& s: myArray )
{
s = s.substr(0,4);
std::cout << s << std::endl;
}
return 0;
}
http://www.cplusplus.com/reference/string/string/substr/
or
https://en.cppreference.com/w/cpp/string/basic_string/substr
Or you may want use resize which let the resulting string to be at a fixed size, if needed, filled up by a char which you can add as parameter.
https://en.cppreference.com/w/cpp/string/basic_string/resize
What you did is simply replacing a character inside the string. So if you have a string "abcdef" you will get "abcd\0e" which is not what you expect. You can see that yourself by printing out each of the chars like this:
myArray[0][4]='\0';
for ( auto&c: myArray[0] )
{
std::cout << (int) c << std::endl;
}
If you print it as a c-string, the output looks like the string is shorted, but it is really not! This one looks well but is wrong:
myArray[0][4]='\0';
std::cout << myArray[0].c_str() << std::endl;
Why?:
Quite simple: std::cout uses for printing std::string a different method than for printing c-style strings.
If you know where you want to cut, this is why substr function exist. Its a method from string, look at the documentation http://www.cplusplus.com/reference/string/string/substr/.
Hope it helps.

How to erase non-alphabet characters from a string without going out of range

I am trying to this function to return without numbers, spaces, or other characters and I am supposed to use the .erase function. I understand that my loop keeps going out of range, but I have no clue how to fix it and I've been stuck on this for a while. If the user types "dogs are a lot of fun" and I need the function to return and output "dogsarealotoffun" Thanks for the help.
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();
while (input[i] < size){
if (isalpha(input[i])){
i++;
}
else
input.erase(input[i]);
}
return input;
}
int main() {
string input;
cout << "Enter a string to test: ";
getline(cin, input);
cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
EDITED: I was too hasty in my previous answer (as I am learning I need to speak from tested code rather than off the top of my head) and needed to debug. The problem is in the else case you need to erase the char, NOT increment i because the length of the string just changed, and also since the length of the string changed you need to reset size to be the new length. Sorry for the hasty answer earlier, I was speaking without actually using the compiled code.
#include <iostream>
#include <cctype>
#include <string>
//function to output string without spaces, numbers, or punctuations
std::string alphabetOnly (std::string input){
int size;
int i= 0;
size = (int)input.size();
while (i < size){
if (isalpha(input[i])){
i++;
}
else{
input.erase(i,1);
//do not increment i here since the index changed becauase of erase
size = (int)input.size();
}
}
return input;
}
int main() {
std::string input;
std::cout << "Enter a string to test: ";
std::getline(std::cin, input);
std::cout << input;
std::cout << "alphabetOnly: " << alphabetOnly(input) << std::endl;
return 0;
}
something like this:
#include <iostream>
#include <string>
#include <algorithm>
//function to output string without spaces, numbers, or punctuations
std::string alphabetOnly (std::string input)
{
auto not_alpha = [](char c) { return !std::isalpha(c); };
input.erase(std::remove_if(begin(input),
end(input),
not_alpha),
std::end(input));
return input;
}
int main() {
std::string input;
std::cout << "Enter a string to test: ";
getline(std::cin, input);
std::cout << "alphabetOnly: " << alphabetOnly(input) << std::endl;
}
http://coliru.stacked-crooked.com/a/340465d41ecd8c8e
There's quite a few things wrong with your code, but to start with here's your main error corrected.
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();
while (i < size){
if(isalpha(input[i]))
{
i++;
}
else
input.erase(input.begin( ) + i );
}
return input;
}
int main() {
string input;
cout << "Enter a string to test: ";
getline(cin, input);
cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
But this is awfully inefficient because you swhift all the remaining unchecked characters each time you delete.
You should use something like
input.erase( remove_if( input.begin(), input.end(), not( isalpha ) ), input.end( ));
This is known as the remove-erase idiom, whihc you can lookup anywhere.

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

taking strings with whitespaces in c++

#include<iostream>
using namespace std;
int main()
{
string p;
int n,i;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>p;
cout<<p<<"\n";
}
return 0;
}
hiii..
i wanna take two strings and then print them one by one as in prog. but when i take n=2 and input the string "I wanna go"
it gives the output :
i
wanna
and it didn't ask me for second string.it is taking the string until it gets a whitespace.what should i do to resolve this?
You have to change the initial value of your iteration variable i in you for statement to the following one:
for(i=0;i<=n;i++)
Consider using std::getline.
std::string name;
std::getline(std::cin, name);
The above example is summarized from:
std::cin input with spaces?
Instead of operator >> you should use function std::getline. For example
#include <iostream>
#include <limits>
int main()
{
int n;
std::cin >> n;
std::cin.ignore( std::numeric_limits<std::streamsize>::max() );
// or simply std::cin.ignore();
for ( int i = 1; i <= n; i++ )
{
std::string p;
std::getline( std::cin, p );
std::cout << p << "\n";
}
return 0;
}