0

I am trying to make a program which declares an array(string) which will gain its size and value during the run time , user will input them. This is a code , but it fails giving error: initializer failed to determine size of text.

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
char text[] = txt;
x = sizeof(text[]);
cout << x;
return 0;

This is another one, it gives error: storage size of text isn`t known.

 char text[];
 int x;
cout << "Enter the text\n";
cin >>   text;
 x = sizeof(text[]);
cout << x;
  return 0;
  • sorry the title was supposed to be , Array will be given value and size during run time –  Jun 08 '16 at 15:11
  • What you really want is a [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) – NathanOliver Jun 08 '16 at 15:11
  • @MohamedKhaled You can [edit](http://stackoverflow.com/posts/37706418/edit) your question to make any necessary changes (e.g., Fix the title) – James Adkison Jun 08 '16 at 15:15

3 Answers3

2

Better use the string type. Then you can call the method size() for that string.

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
x = txt.size();
cout << x;
return 0;
kemis
  • 4,404
  • 6
  • 27
  • 40
  • it`s ok but i need , the array . now iam stucked here char text[x] = txt; , it gives , error; array must be initialized with a brace-enclosed initializer –  Jun 08 '16 at 16:10
  • For simple questions like this please "google" it http://stackoverflow.com/questions/13294067/how-to-convert-string-to-char-array-in-c – kemis Jun 08 '16 at 16:17
0
char text[] = txt;

is wrong.

You can't cast a std::string type to a char[] array straight away.

If you want to access the raw pointer to the char[] array maintained within the std::string, use the std::string::c_str() or std::string::data() member functions.


I actually don't get what kind of capers you're doing with char[], but I'd rewrite your code simply like this:

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
// char text[] = txt; <<<<< remove
x = txt.size(); // <<<<<< change
cout << x;
return 0;

If there's further need for [const] char* types, you can use the functions as mentioned in the 1st part of my answer.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

ok , i`ve found it

string txt;
int x;
cout << "Enter the text\n";
getline  (cin,txt);
x = txt.size();
 char text[x];
strcat(text,txt.c_str());
cout <<"string="<<txt<<endl;
for (i=0;i<=x;i++){
    cout << "text["<<i<<"] : "<<text[i]<<endl;
}
return 0;