Reputation:
I am new. I am learning C++. I am trying to append specific item form a string to another string using for loop. But I am unable to do it. I found nothing helpful searching on the internet.
My code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string statement, newStatement = "";
cin >> statement;
for (int i = 0; i < statement.length(); i = i + 2)
{
newStatement.append(statement[i]);
}
cout << newStatement;
return 0;
}
Please help me how can I do that. Thank you.
Upvotes: 2
Views: 950
Reputation: 75062
You can use std::string::push_back
to append one character to a string.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string statement, newStatement = "";
cin >> statement;
for (int i = 0; i < statement.length(); i = i + 2)
{
newStatement.push_back(statement[i]); // use push_back instead of append
}
cout << newStatement;
return 0;
}
Upvotes: 2