How to take input and output of a string?

This is a very easy question but I always struggle with it. I’m always confused about what are some good practice to take string input and output them.
suppose I have to take the input of lower case English alphabets [a - y].(not z)

string s;
cin>>s;
for(int i = 0; i < s.lenght(); i++)
cout<<s[i]+1;

Above I was trying to take the input of the string and printing the same string while incrementing the ASCII value of each character of it.
Is this the right to do it?
Or should I save this append this character into a new string and then print the result instead of using the cout again and again,
Or should I take the input in char array then calculate its length and then increment the array?

There are many ways for it and I’m unable to find out which one to choose? and which is more reliable. where to go for char array and what is the caveat with using cout multiple times?
Please clarify my google search is making this more confusing to me.

  1. Use s.size() to get length of string since it is constant time.
  2. Use (char)(s[i]+1) if you need to directly print.

Cout is a flushing operation and unless you use fast I/O

ios_base::sync_with_stdio("false");
cin.tie(NULL);

the program might give TLE if you are performing cout too many times
Refer this problem

1 Like

I’d just do this:

#include <iostream>

using namespace std;

int main()
{
    string s;
    cin >> s;
    for (auto& letter : s)
        letter++;
    cout << s << '\n';
}
2 Likes

I can confirm this.
I did some tests.

  1. cout each character.
int main() {
	ios_base::sync_with_stdio(false);cin.tie(NULL);
	int n = 1e8, in = 0;
	for (int i=0; i<n; i++) {
		cout << (char)('a'+in);
		++in;
		if (in > 25) {
			in = 0;
		}
	}
	return 0;
}
real	0m5.427s
user	0m2.971s
sys	    0m0.310s
  1. Using string and then cout once (faster).
int main() {
	ios_base::sync_with_stdio(false);cin.tie(NULL);
	int n = 1e8, in = 0;
	string s="";
	for (int i=0; i<n; i++) {
		s+= (char)('a'+in);
		++in;
		if (in > 25) {
			in = 0;
		}
	}
	cout << s;
	return 0;
}
real	0m2.699s
user	0m0.332s
sys	    0m0.344s