Kindly log in to use this feature. We’ll take you to the login page automatically.
LoginGeneral Tech Bugs & Fixes 3 years ago
User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.
Note that you do not initialize your iterator variable i and that you could declare the index within the for-statement as you do not need this variable outside the scope of the for-loop. Furthermore, you can also use a std::string instead of a char array, this also allows for strings longer than the ten characters as you had specified.
EDIT: I assume that you can use C++17 or newer. From C++17 they finally added the non-member version std::size (which I prefer over the member related versions since I read the book effective modern c++ from Scott Meyers). If for some reason you cannot use this function, then you can just replace it by the string member function length, i.e., a.length().
If you only want to print the reverse of the string you could use something like the following
int main()
{
string a;
cout << "Enter String: ";
cin >> a;
for (int idx = size(a) - 1; idx >= 0; --idx)
cout << a[idx];
cout << endl;
}
You may also use the built-in reverse function (see description here). This function actually reverses the string itself.
int main()
{
std::string a;
std::cout << "Enter String: ";
std::cin >> a;
std::reverse(std::begin(a), std::end(a));
std::cout << a << endl;
}
Another option is to manually reverse the string (which doesn't make sense since std::reverse is part of the standard library, but as a learning exercise it might be helpful). Note that we only iterate to half the size of the string as otherwise each element is swapped twice, resulting in the original string.
int main()
{
string a;
cout << "Enter String: ";
cin >> a;
for (size_t idx = 0, n = size(a); idx < n / 2; ++idx)
swap(a[idx], a[n - idx - 1]);
cout << a << endl;
}
No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.
Kindly log in to use this feature. We’ll take you to the login page automatically.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
manpreet
Best Answer
3 years ago
I want to reverse a string by only using a single loop. How can I do it? I tried one simple way but doesn't get the output I wish.