C++ 将在运行时为数组指定值和大小

C++ 将在运行时为数组指定值和大小,c++,arrays,string,C++,Arrays,String,我试图制作一个程序,声明一个数组(字符串),它将在运行时获得其大小和值,用户将输入它们。 这是一个代码,但它无法给出错误:初始值设定项无法确定文本的大小 string txt; int x; cout << "Enter the text\n"; cin >> txt; char text[] = txt; x = sizeof(text[]); cout << x; return 0; stringtxt; int x; cout>txt; 字符文本[

我试图制作一个程序,声明一个数组(字符串),它将在运行时获得其大小和值,用户将输入它们。 这是一个代码,但它无法给出错误:初始值设定项无法确定文本的大小

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

不能更好地使用
字符串
类型。然后可以为该字符串调用方法
size()

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
x = txt.size();
cout << x;
return 0;
stringtxt;
int x;
cout>txt;
x=txt.size();

不能更好地使用
字符串
类型。然后可以为该字符串调用方法
size()

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
x = txt.size();
cout << x;
return 0;
stringtxt;
int x;
cout>txt;
x=txt.size();
库特
这是错误的

不能直接将
std::string
类型强制转换为
char[]
数组

如果要访问
std::string
中维护的
char[]
数组的原始指针,请使用或成员函数


实际上,我不知道你在用
char[]
做什么,但我会像这样简单地重写你的代码:

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
// char text[] = txt; <<<<< remove
x = txt.size(); // <<<<<< change
cout << x;
return 0;
stringtxt;
int x;
cout>txt;
//字符文本[]=txt;
这是错误的

不能直接将
std::string
类型强制转换为
char[]
数组

如果要访问
std::string
中维护的
char[]
数组的原始指针,请使用或成员函数


实际上,我不知道你在用
char[]
做什么,但我会像这样简单地重写你的代码:

string txt;
int x;
cout << "Enter the text\n";
cin >>   txt;
// char text[] = txt; <<<<< remove
x = txt.size(); // <<<<<< change
cout << x;
return 0;
stringtxt;
int x;
cout>txt;
//字符文本[]=txt 好的,我找到了

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;
stringtxt;
int x;
好的,我找到了

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;
stringtxt;
int x;

很抱歉标题应该是,数组将在运行时被赋予值和大小您真正想要的是@MohamedKhaled,您可以对您的问题进行任何必要的更改(例如,修复标题)很抱歉标题应该是,数组将在运行时给定值和大小您真正想要的是@MohamedKhaled,您可以对您的问题进行任何必要的更改(例如,修复标题),您可以编写吗example@MohamedKhaled实际上是为了什么?我是说,如果你能给我写一行代码来解决这个问题,我不明白你在回答中的意思,你能写吗example@MohamedKhaled实际上是为了什么?我的意思是,如果你能给我写一行代码来解决这个问题,我在回答中没有理解你的意思。没关系,但我需要数组。现在我在这里卡住了char text[x]=txt,它给出,错误;数组必须用括号内的初始值设定项进行初始化对于像这样的简单问题,请“谷歌”它可以,但我需要数组。现在我在这里卡住了char text[x]=txt,它给出,错误;数组必须用大括号内的初始值设定项初始化。对于像这样的简单问题,请“谷歌”它