【问题标题】:Array will be given value and size during run time数组将在运行时被赋予值和大小
【发布时间】:2016-06-08 15:10:17
【问题描述】:

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

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

这是另一个,它给出了错误:文本的存储大小未知。

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

【问题讨论】:

  • 对不起,标题应该是,数组将在运行时被赋予值和大小
  • 你真正想要的是std::string
  • @MohamedKhaled 您可以edit您的问题进行任何必要的更改(例如,修复标题)

标签: c++ arrays string


【解决方案1】:

最好使用string 类型。然后你可以为那个字符串调用方法size()

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

【讨论】:

  • 没关系,但我需要数组。现在我卡在这里 char text[x] = txt; , 它给出 , 错误;数组必须用大括号括起来的初始化器进行初始化
  • 对于这样的简单问题,请“谷歌”它stackoverflow.com/questions/13294067/…
【解决方案2】:
char text[] = txt;

错了。

您不能立即将 std::string 类型转换为 char[] 数组。

如果您想访问指向std::string 中维护的char[] 数组的原始指针,请使用std::string::c_str()std::string::data() 成员函数。


我实际上不明白你在用char[] 做什么,但我会像这样重写你的代码:

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

如果还需要[const] char* 类型,您可以使用我的答案第一部分中提到的功能。

【讨论】:

  • 你能写出例子吗
  • @MohamedKhaled 实际上是为了什么?
  • 我的意思是,如果你能写给我解决问题的代码行,我没明白你的意思
【解决方案3】:

好的,我找到了

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2021-08-06
    • 2021-03-15
    • 1970-01-01
    • 2021-09-06
    • 2018-03-31
    • 2017-11-10
    相关资源
    最近更新 更多