int main()
{
int t;
cin>>t;
while(t--)
{
string s;
getline(cin,s);
cout<<s.at(0);
}
return 0;
}
I tried to run this code but it says out_of_range error. This code is not even taking in the string input.
You are mixing line-based input with non-line-based input.
int main() { int t; cin>>t;
When the user enters "123" and then presses the enter key, the "123" part of the input is parsed and ends up as the number 123 in t
, but the linebreak resulting from the enter key will remain in the input buffer.
That's non-line-based input.
while(t--) { string s; getline(cin,s);
The std::getline
function reads everything until a linebreak is encountered. The linebreak from above is still there, so a linebreak is encountered immediately and s
remains empty.
That's line-based input.
std::getline
also consumes the linebreak it has encountered, but this doesn't help you much anymore:
cout<<s.at(0);
s
has size 0 and at(0)
tries to access the 1st element. at
is required to throw std::out_of_range_error
when you try to access a non-existing element.
A good solution would be to switch exclusively to line-based input on the top input layer. Read everything as lines and parse the individual lines as required. Use std::stoi
to convert a string to an integer number.
Here is an example:
#include <iostream>
#include <string>
int main()
{
std::string input;
std::getline(std::cin, input);
int t = std::stoi(input);
while(t--)
{
std::string s;
getline(std::cin, s);
std::cout << s.at(0);
}
}
Note that you should consider adding more error handling to your code. What happens when the user enters a negative number?