0

In my c++ code i want to write character array s[n] instead of writing s[10]. where n is size is the array, it is given by the user at the run time. But its not taking input. Its only taking n, not string.

I got the Output like this,

Enter size : 10

Enter String :

String :

    #include<iostream>
    #include<cstring>
    using namespace std;

    int main()
    {
       int n;
       cout<<"Enter size : ";
       cin>>n;
       char s[n];
       cout<<"Enter String : \n";
       cin.getline(s,n);
       cout<<"String : \n";
       int l=strlen(s);
       cout.write(s,l);
       return 0;
    }
Santhosh R
  • 31
  • 3
  • 7
    Variable length arrays (VLAs) are not part of the C++ language, although some compilers support them as an extension: [Variable Length Array (VLA) in C++ compilers](https://stackoverflow.com/q/39334435/10871073). But why are you using C-style strings in C++ - just use `std::string`, instead. – Adrian Mole May 02 '21 at 16:04
  • // you might consider using dynamic memory .... char* s = new char[n]; cout << "\n Enter chars : "; cin.getline(s,n); cin.ignore(); cout << " ( chars are: '" << s << "')"; // use smart ptr OR remember to delete the allocation – 2785528 May 02 '21 at 18:34

2 Answers2

5

cin.ignore() can be used to patch your problem, as mentioned in this post:

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    int n;
    cout<<"Enter size : ";
    cin>>n; n++;
    char s[n];
    cout<<"Enter String : "; cin.ignore();
    cin.getline(s,n);
    cout<<"String : ";
    cout.write(s,n);
    return 0;
}

Result:

Enter size : 10
Enter String : 1234567890
String : 1234567890

*Note: Ran in Code::Block 20.03, g++ version 6.3.0, Windows 10, 64 bit.

But, as a comment mentioned above, VLAs or Variable Length Array(s) are not part of the standard in C++, although g++ and clang++ compiler support them.

And as @Kevin Pastor specified, the easiest way would be to use std::string that does all the work of data allocation.

Sample:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s; cout << "Your string: ";
    getline(cin, s);
    cout << "String: " << s;
}

Sample output:

Your string: 1234567890
String: 1234567890

More info in here about VLAs.

3

As mentionned in a comment, in C++, you cannot create a variable length array. This said, there's plenty of other ways you can address the problem. The easiest one would be to use std::string that does all the work of data allocation. If your situation requires you to use a char array, you could allocate some memory for an array as so: char * s = new char[n];. This would create a pointer to a memory location where n characters could be stored.

Kevin Pastor
  • 761
  • 3
  • 18