【发布时间】: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