【问题标题】:Using an integer variable for a character array size [duplicate]对字符数组大小使用整数变量
【发布时间】:2021-06-08 01:32:36
【问题描述】:

我正在尝试使用 fstream 读取文本文件,然后将字符串转换为字符数组。但是,当我创建一个整数“n”,即字符串的大小加 1 时,我不能使用它来初始化数组的大小。我收到一条消息说,“表达式必须有一个常量值。” 我试图阅读的文本文件只是说,“这是一条消息”。长度为 17 个字符。当我输入数字 18 (char messageArray[18]) 时,一切正常。但我希望能够根据我的短信长度传递一个值。

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


int main() {

// Read the message text file and save it to a string
    fstream newfile;
    string message;
    newfile.open("input.txt", ios::in);
    if (newfile.is_open()) {
        getline(newfile, message);
        newfile.close();
    }

// Convert the message string to an array of characters
    int n{};
    n = message.size() + 1;
    char messageArray[n];
    strcpy_s(messageArray, message.c_str());
    cout << messageArray << endl;



    


    return 0;
}

【问题讨论】:

  • C/C++ 中数组的大小必须是编译时间常数。您应该动态分配缓冲区或只使用std::vector
  • 从文件中读取的代码只读取一行。这是你的意图吗?
  • @user7860670 不。 C中数组的大小不需要是编译时间常数。这个问题是关于 C++ 的。
  • @eerorika Nouveau C 方言(可选)VLA 支持不是 C.
  • @user7860670 VLA 支持在 C99 中不是可选的。在后来的 C 标准中它可能是可选的,但无论是否可选,它仍然是标准 C。

标签: c++ arrays string io fstream


【解决方案1】:

你不能这样做。数组变量的大小在 C++ 中必须是编译时常量。

您也不需要这样做。 message 已经拥有一个动态空终止数组。无需将其复制到其他地方。如果您需要字符串的副本,则创建另一个 std::string 对象。

【讨论】:

  • 这是有道理的。谢谢!
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 2019-12-28
  • 2014-10-05
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多