【问题标题】:Creating array after getting variable in other function在其他函数中获取变量后创建数组
【发布时间】:2016-12-04 16:32:12
【问题描述】:

一个文本文件如下所示:

3
String
String2
String3

我必须创建一个函数来从文本文件中读取所有字符串,将它们保存到数组中,然后在主函数中显示它。例如

void reading(int & count, string strings[]) {
ifstream fd "text.txt";
fd >> count;
for (int i=0; i<count; i++)
fd >> strings[i];
fd.close();

主要功能:

int main() {
int count=0;
string strings[100];
reading(count, strings);
for (int i=0; i<count; i++) 
cout << strings[i] << endl;

字符串的数量写在文本文件的第一行。我怎样才能创建一个正好是那个数字的数组?我需要它能够在主要/其他功能中访问它。 (例如写入另一个文本文件的函数)。

【问题讨论】:

  • 你能用std::vector&lt;std::string&gt;代替数组吗?
  • 我想对你说实话......帮助别人真的很酷,但你应该始终考虑我们必须从某个地方开始。这意味着您必须先开始才能越过终点线

标签: c++ arrays file memory-management dynamic-memory-allocation


【解决方案1】:

如果有一个非常重要的原因需要对数组执行此操作,请使用std::new,如下所示:

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

int reading(string** str_array, int& size,  string filename) {
    ifstream infile(filename.c_str());
    if(!infile) {
        cerr << "Unable to access file!\n";
        return -1;
    }
    int n = 0;
    infile >> size;
    try{
        *str_array = new string[size];
        string str;
        for (; n < size && infile; ++n) {
            infile >> str;
            (*str_array)[n] = str;
        }

        if (n != size)
            cerr << "ERROR, read less than " << size << " strings!!\n\n";
    } catch(bad_alloc& exc) {
        return -2;
    }
    return 0;
}


int main() {
    string* str_array = NULL;
    int size;
    if(reading(&str_array, size, "test.txt")) {
        cerr << "Din't read file, exiting...\n";
        return -1;
    }
    for(int i = 0; i < size; ++i)
        cout << str_array[i] << endl;

    delete [] str_array; // DO NOT FORGET TO FREE YOUR MEMORY
    str_array = NULL;

    return 0;
}

输出:

C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3

但是,您在 中并且没有为此使用 std::vector

看看它是多么简单:

#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

int reading(vector<string>& v, string filename) {
    ifstream infile(filename.c_str());
    if(!infile) {
        cerr << "Unable to access file!\n";
        return -1;
    }
    int N = -1, n = 0;
    infile >> N;
    string str;
    for (; n < N && infile; ++n) {
        infile >> str;
        v.push_back(str);
    }

    if (n != N)
        cerr << "ERROR, read less than " << N << " strings!!\n\n";
    return 0;
}

int main() {
    vector<string> v;
    if(reading(v, "test.txt")) {
        cerr << "Din't read file, exiting...\n";
        return -1;
    }
    for(size_t i = 0; i < v.size(); ++i)
        cout << v[i] << "\n";
    return 0;
}

输出:

C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3

编辑:

我们必须传递一个指向我们想要修改的指针(即string*),否则我们应用的更改不会发生。自己测试一下,将string* 作为参数传递而不是string**,修改函数的主体,然后会发生什么。

为了理解这个想法,假设我们想要写入指针,新地址,new 给了我们并保存了请求的内存。我们确实在函数中写入了该地址,但是当函数终止时,我们希望更改是持久的。以我的Functions in C 为例。

【讨论】:

  • 这可能是一个家庭作业,如果确实如此,在课堂上使用类似的东西是有限制的。
  • @M4rc 对此做出假设应该是回答者必须遵循的逻辑的一部分,我的意思是什么鬼?!如果是家庭作业,请说明。不过好吧,那我也会提供另一个版本的……
  • 我同意。理想情况下,人们会相应地标记这些东西。但我们从什么时候开始生活在一个理想的世界里了?我认为这是家庭作业的唯一原因是因为很多个月前我不得不做一个类似的程序。但话说回来,SO 上有些人问人们如何编写整个 CLI 界面。
  • @M4rc 是真的......不过,我更新了我的帖子,好吗?
  • 非常如此 =]。我喜欢编程的一件事——有不止一种方法可以达到预期的最终结果。我会在 delete 语句之后设置str_array = 0; ,但这只是因为旧习惯很难检查/留下悬空指针。
【解决方案2】:

在堆上分配一个数组,像这样:

std::string* stringArr = new std::string[(place amout of strings here)];

并且别忘了在main()的末尾删除

delete stringArr[];

堆上的变量/数组是动态的,因此大小不必固定!

std::string* → 这是一个指针,指向你的内存中这个数组的起始地址。 (只是为了让您的计算机知道它在哪里)

stringArr → 数组名

new → 分配新内存

std::string[size] → 说分配多少

我看过一些关于“向量”的答案。如果您想使用它们,您可以查看此页面以获取更多信息! → Vector documentation

【讨论】:

  • 您应该使用向量,因为它会为您管理内存。
  • @Kariem 会的,但是在您了解向量之前,您应该学习基础知识!导致向量使用堆上的内存
  • +1 - 了解矢量、地图等如何工作背后的基本原理的价值远比简单地遵循向所有事物扔 STL 容器的暴民心态更为重要。
  • @tistCoder 当然它使用堆上的内存......我说过它会为你管理内存,所以当它超出范围时它会释放它已分配的堆上的内存.
  • @M4rc 谢谢。看起来这是他的作业,他们的问题是学习理解
【解决方案3】:

使用向量

#include <vector>
#include<fstream>
#include <iostream>
using namespace std;
void reading(int & count, vector<string> * strings) {
    ifstream fd("text.txt");
    fd >> count;
    string T;
    for (int i=0; i<count; i++)
    {
        fd >> T;
        strings->push_back(T);
    }
    fd.close();
}

int main() {
    int count=0;
    vector<string> strings;
    reading(count, &strings);
    for (int i=0; i<count; i++) 
        cout << strings[i] << endl;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2019-01-30
    • 1970-01-01
    • 2018-05-20
    相关资源
    最近更新 更多