【问题标题】:How do I make a regular string array into a const string array after it has been read from a file in C++?从 C++ 中的文件读取后,如何将常规字符串数组转换为 const 字符串数组?
【发布时间】:2023-03-17 15:54:01
【问题描述】:

我有一个字符串数组,我从一个函数传递到我的主函数中,我想将该数组更改为一个常量,一旦它位于主函数中,以便其他函数无法操作它。我不知道该怎么做。我是一名学生,不能为这项作业使用指针。这是我所拥有的:

//declare variables
string name;
const int size = 11;
string ans[size];
const string corrAns[size] = { "C++","for","if","variable","function", "return",
    "array","void","reference","main", "prototype" };
const string studAns[size];
double percent;

// read file
readFile(name, ans, size);

// calculate percentage
percent = calculatePercentage(corrAns, studAns, size);

// print out report
printReport(name, percent, corrAns, studAns, size);

system("Pause");
return 0;
}

程序的其余部分按我想要的方式工作,但是我不确定我应该如何有效地将ans 转移到studAns,并且在任何地方都没有成功找到答案。

【问题讨论】:

  • 使用const std::string* 作为函数参数的类型。
  • 为什么你认为你需要将ans转移到任何地方而不是直接使用它?
  • 我作为一名专业程序员工作了很多年,但我从未编写过代码来在main 中间构造一个 const 数组。你不能使用指针...你可以使用引用吗?
  • 我可以使用引用而不是指针。我们只是在学习指针,这应该使用我们已经介绍过的东西。

标签: c++ arrays constants data-transfer


【解决方案1】:

如何将常规字符串数组从 C++ 文件中读取后变成 const 字符串数组?

你真的不能。您可以做的是通过将const std::string* 指针或const std::string[] 数组传递给函数来防止后续操作发生变化。


但是,惯用的 c++ 方法根本不使用原始数组,而是使用 std::vector<std::string>

std::vector<std::string> ans(size);
const std::vector<std::string> corrAns = {   
    "C++","for","if","variable",
    "function", "return",
    "array","void","reference","main", "prototype" };
std::vector<std::string> studAns(size);

为了防止函数改变值,你应该有类似的签名

double calculatePercentage(
    const std::vector<std::string>& corrAns
  , const std::vector<std::string>&  studAns);

void printReport(
    const std::string& name, double percent
  , const std::vector<string>& corrAns
  , const std::vector<string>& studAns);

请注意,size 不需要,std::vector 已经跟踪它。

【讨论】:

  • "你不能真的" 对 const 数组的引用可以正常工作。
  • @juanchopanza 嗯,这不会改变原始数组的常量,这就是我的意思。
  • 确实如此。它只为传递给它的函数提供它的 const 视图。我认为这对 OP 来说已经足够好了,但他们的要求还不够清楚。
  • 所以我不确定向量是否可以在这里使用。我们得到了三个要使用的函数原型: 'void readFile(string &, string[], const int);双计算百分比(常量字符串 [],常量字符串 [],常量 int); void printReport(string, double, const string[], const string[], const int);'
  • 如果我完全取出 studAns,那么数组可以通过并且代码很好,但是我必须根据我的教授规范使用 const 字符串 studAns[]。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 2021-12-13
  • 1970-01-01
相关资源
最近更新 更多