2
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string>  a;
    a.push_back("1 1 2 4");
    a.push_back("2 3 3 3");
    a.push_back("2 2 3 5");
    a.push_back("3 3 3 3");
    a.push_back("1 2 3 4");
    for (int i=0;i<a.size();i++)
        for(int j=0;j<a[i].length();j++)
            cout<<a[i].at[j];
    return 0;
}

Hi,when I run the code above,there is an error as below:

error C2109: subscript requires array or pointer type

Please help me and tell me why,thanks!

10
  • 4
    Call at with round brackets: at(j) Commented Oct 17, 2013 at 8:43
  • 3
    Or don't use at at all. I've never found a situation where its semantics are appropriate (especially with std::string). Commented Oct 17, 2013 at 8:44
  • @JamesKanze: With vector, sometime at() is useful and is needed. Commented Oct 17, 2013 at 8:51
  • @JamesKanze: what is the specific point of semantic on std::string that worries you ? I usually recommend using at() rather than [] to protect against out of bounds aspects. Commented Oct 17, 2013 at 8:54
  • 1
    @Nawaz Yes. If you plan to catch the exception, and do something with it, then by all means, at is the solution. But beware in actual applications. If a bounds check error is an actual error (violation of a precondition), you don't want to unwind the stack (which may be corrupted); you want to get out of the process executing as little code as possible. If the internal state is corrupted, even executing a destructor could make things even worse. Commented Oct 17, 2013 at 11:17

2 Answers 2

7

at is a function, need to be called with () not []

update

cout<<a[i].at[j];
//           ^^^

to

a[i].at(j)
//   ^^^^^

To output string, you don't need to cout each char, just do

for (int i=0; i<a.size(); i++)
{
   std::cout << a[i] << "\n";
}
std::cout << std::endl;

Or if C++11:

for(auto const & s : a)
{
   cout << s << "\n";
}
Sign up to request clarification or add additional context in comments.

Comments

0

It is more simpler to use the range-based for statement. For example

for ( const std::string &s : a )
{
    for ( char c : s ) std::cout << c;
    std::cout << std::endl;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.