Umar Malik
Umar Malik

Reputation: 55

How do I declare an array of unknown size then take input till I desire and then get the size of the array?

I'm trying to declare an array of size 10,000. Preferably a character array. Then I may take the input of any size n(<=10,100). And I want to find this n.

I have a code which is not working.

int main()
{
    char arr[10000];
    cin >> arr;
    cin.sync();
    int l=0;
    for(int i=0; ; i++)
    {
        if(arr[i]=='\n')
            break;
        l++;
    }
    cout << l;
    return 0;

Input : Hell I expect the output to be 4, but the actual output is 4482.

Upvotes: 2

Views: 1185

Answers (3)

Faruk Hossain
Faruk Hossain

Reputation: 1203

Use standard C++ library normally. #include <string> does this task easily.

string arr;
cin >> arr;
cin.sync();
int l = arr.length();
cout << l;
return 0;

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234635

You can't do that in standard C++. But you can use

std::vector<char> arr;

and arr.resize(/*ToDo - size here*/) when you need to. The std::vector memory management is also superior to using a large fixed-size array with automatic storage duration.

That said, a std::string is probably the best choice in your case:

std::string the_standard_library_is_fantastic;
std::cin >> the_standard_library_is_fantastic;

followed by

std::cout << the_standard_library_is_fantastic;

Your assumption that arr is in a sense terminated with a '\n' is not correct.

Upvotes: 3

Blaze
Blaze

Reputation: 16876

cin >> arr; puts a C-style string into arr, which is terminated with '\0', not with '\n' (even though you press enter to send the input to your program). To get that expected output of 4, you need to change this

if (arr[i] == '\n')

To this:

if (arr[i] == '\0')

Upvotes: 1

Related Questions