user-inputted unsized arrays...?

why can you not have an unsized array that is user-inputted? for example, the following doesn't work

1
2
3
4
5
6
7
8
9
10
11
12
 

int main()
{
     char str1[];
     
     cin >> str1;
     cout << str1;

     return 0;
}
There are standard containers as for example vector or list that dynamiclally allocate storage for their elements.
As for string there is such a class as std::string in the STL.

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main()
{
   std::string str;

   std::cin >> str;

   std::cout << std << std::endl;

   return ( 0 );
}
Last edited on
You could also do it with a dynamically allocated array, but that requires user input :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
    cout << "How many letters long is your name? ";
    int len;
    (cin >> len).get();
    char * name = new char[len+1];
    cout << "What is your name? ";
    cin.getline(name, len+1);
    cout << "Sup " << name << endl << "!";
    return 0;
}
thanks, really helped
dynamically allocating memory with new or new[] also requires that you use delete or delete[] afterwards - otherwise your program will "leak" memory (There are plenty of ways in which you can accidentally leak memory in bigger and more complicated programs). For this reason, the std::string and std::vector should be preferred as your first choice.
Topic archived. No new replies allowed.