1
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.

Pavneet_Singh
  • 34,557
  • 5
  • 43
  • 59
Buetman
  • 7
  • 5
  • 2
    *This code is not even taking in the string input.* -- That's the reason. Your string is empty and you're trying to access the first element. – PaulMcKenzie Dec 10 '16 at 05:48

2 Answers2

0

You can use cin.sync() function to clear extra input buffer.

The code like this:

int main()
{       
    int t;
    cin >> t;
    cin.sync(); // add this line
    while(t--)
    {
        string s;
        getline(cin, s); 
        cout<<s.at(0);          
    }    
    return 0;
}

The original code to make the string that is empty and you're trying to access the first element. So it says out_of_range error.

Albert
  • 29
  • 1
  • 5
0

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?

Christian Hackl
  • 25,191
  • 3
  • 23
  • 53