Reputation: 1
how to make a program to take 4 letters from the front where the word you input has 10 letters, with the words free with pointers?
#include <iostream>
using namespace std;
int main(){
string phrase;
cout << "Input : ";
cin >> phrase;
cout << "Output: " << phrase.substr(0, 4);
// i dont know how to use pointers
return 0;
}
I want to do like that to the output but use pointers, what can I do?
Upvotes: 0
Views: 43
Reputation: 1
I want to do like that to the output but use pointers, what can I do?
Given that the input string at least 10
characters long, you can use std::string::c_str
as shown below:
const char* bPtr = phrase.c_str();
const char* ePtr = phrase.c_str() + 4;
std::string result(bPtr, ePtr);
cout << "Output: " << result;
Or a one liner:
std::string result(phrase.c_str(), phrase.c_str() + 4);
Or
std::string result(phrase.c_str(), 4);
Note that you can also use iterators using std::string::begin
instead of pointers.
std::string result(phrase.begin(), phrase.begin() + 4);
Upvotes: 2