1

What is wrong in this code? I want to make a dynamic string array using string*, not collections, vectors, etc.

    int abc = 4;
string* abcdef = new string[abc];
for (int i = 0; i < abc; i++)
{
    cin >> abcdef[i];
}

It doesnot give any error but the data I enter is not appearing in locals box in VS2012.

Regards

2 Answers2

3

This works just fine:

#include <iostream>
#include <string>

int main()
{
    int count = 4;
    std::string* stringArray = new std::string[count];
    for (int i = 0; i < count; i++)
    {
        std::cin >> stringArray[i];
    }

    for (int i = 0; i < count; i++)
    {
        std::cout << "stringArray[" << i << "] = " << stringArray[i] << std::endl;
    }

    delete [] stringArray;
    return 0;
}

Though, the better solution would still be:

int main()
{
    std::vector<std::string> stringVector;
    std::cout << "Enter Strings (Ctrl-Z to finish):" << std::endl;
    std::copy(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string>>(stringVector));
    std::copy(stringVector.begin(), stringVector.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    return 0;
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • Too much of `std::`, why not `using namespace std;`? – thefourtheye Aug 23 '13 at 13:53
  • Unless we have C++11 supported compiler, it would fail with `std::back_inserter>` – thefourtheye Aug 23 '13 at 14:02
  • 1
    It avoids potential naming conflicts, especially when displaying code for someone else to use and not knowing what compiler they are using, which libraries they are including, etc. I rarely use `using namespace [fill in the blank];` See http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice and http://stackoverflow.com/questions/1265039/using-std-namespace – Zac Howland Aug 23 '13 at 14:02
  • @thefourtheye: There is nothing wrong with `std::back_inserter>` in any version of C++. The only change you would have to make in older versions is to separate the ">>" so the compiler does not try to treat it like an operator. But that changes it to `std::back_inserter >`. The caveat to that: `std::istream` did not properly support insertion and extraction of `std::strings` in most compilers prior to the new standard. – Zac Howland Aug 23 '13 at 14:04
  • @ZacHowland Yes. That's exactly what I meant :) – thefourtheye Aug 23 '13 at 14:05
3

Oh, looks like your question is about VS debugger.

That's how VS debugger shows contents of a pointer. It doesn't know it's an array, so it just shows you what it points to - the first element. To show all of them in watch window type "abcdef, 4" (where 4 is size of an array, obviously).

Artem Tokmakov
  • 1,135
  • 10
  • 7