0

I have a code with string, and I need to get an output of every second inputted character.

I don't understand how to do that at all.

Example: If you input 123 56, output should be 135.

Please, help me to do that.

#include<iostream>
using namespace std;
int main(){
    string str;
    cout<<"Enter a String:";
    getline(cin,str);
    cout<<"You entered: ";
    cout<<str<<endl;
    
    // What should I write here?.
    
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • A `std::string` holds an array of `char`. You can iterate over those elements. So what if you do that with a step of 2? – JHBonarius Dec 22 '20 at 13:56
  • Iterate over your `str` string and print out every second caracter: `for (int i = 0; i < str.size(); i += 2) ...` etc. – vahancho Dec 22 '20 at 13:56

2 Answers2

0
#include<iostream>
using namespace std;
int main(){
    string str;
    cout<<"Enter a String:";
    getline(cin,str);
    cout<<"You entered: ";
    cout<<str<<endl;
    
    cout<<"The output string is"<<endl;
    for(int i=0; i<str.size(); i=i+2)
    {
        cout<<str[i];
    }
    
}

The output is:

Enter a String:You entered: 123 56
The output string is
135
Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
0

Alright here is how can you achieve your expected output. First of all you have to get the length of string. Once you have got the length of string so you can loop through the string for every 2nd character since string is array of characters :)

int main()
{
string num;
cout << "Enter a string: ";
getline (std::cin, num);  
for(int i=0; i< num.length(); i+=2) {
cout << num[i];      

} }

farhan meo
  • 37
  • 1
  • 1
  • 5