将文件读取到数组中并从函数中返回它,C++。

在 Lua 中,我有这样一个函数将文件读入数组中:

function readFile(file)
  local output = {}
  local f = io.open(file)
  for each in f:lines() do
    output[#output+1] = each
  end
  f:close()
  return output
end

在 C ++ 中,我尝试这样写:

string * readFile(file) {
  string line;
  static string output[] = {};
  ifstream stream(file);
  while(getline(stream, line)) {
    output[sizeof(output)+1] = line;
  }
  stream.close();
  return output;
}

我知道你不能从函数返回数组,只能返回指针。所以我这样做:

string *lines = readFile("stuff.txt");

然后它给我错误信息cannot convert 'std::string {aka std::basic_string<char>} to' std::string* {aka std::basic_string<char>*}' in intialization string *lines = readFile("stuff.txt");

有人能告诉我这里出了什么问题吗?是否有更好的方法将文件读入数组中?

编辑: 我将使用返回的数组使用for循环进行值匹配。在Lua中,这将写成:

for _, each in ipairs(output) do
  if each == (some condition here) then
    --Do Something
  end
end

如何在C++中使用向量(根据Jerry Coffin的答案)来做到这一点?

编辑2: 由于某些原因,我无法正确匹配向量。我在一个单独的测试文件中编写了代码。

int main() {
  vector<string> stuff = read_pass();
  cout << stuff.size() << endl;
  cout << stuff[0] << endl;
  if (stuff[0] == "admin") {
    cout << "true";
  }
  else {
    cout << "false";
  }
  return 0;
}

read_pass()的样子:

vector<string> read_pass() {
  ifstream stream("stuff.txt");
  string line;
  vector<string> lines;
  while(getline(stream, line)) {
    lines.push_back(line);
  }
  stream.close();
  return lines;
}

stuff.txt的样子:

admin
why?
ksfndj

我只是放了一些随机的行来测试代码。每次编译和运行main.cpp时,我得到的输出是:

3
admin
false

那么为什么代码没有正确匹配呢?

编辑3:

所以,我决定尝试这个方法:

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include "basefunc.h"

using namespace std;

int main() {
  string storedUsrnm;
  string storedPw;
  string pw = "admin";
  string usrnm = "admin";
  ifstream usernames("usrnm.accts");
  ifstream passwords("usrpw.accts");
  while(getline(usernames, storedUsrnm)) {
    getline(passwords, storedPw);
    print("StoredUsrnm " + storedUsrnm);
    print("StoredPw: " + storedPw);
    if (storedUsrnm == usrnm && storedPw == pw) {
      print("True!");
      return 0;
    }
  }
  print("False!");
  return 0;
}

其中print()是

void print(string str) {
  cout << str << endl;
}

这仍然打印false,最后,这让我相信,由 ifstream 读取的 "admin" 与 "admin" 字符串不同。有什么解释吗?还是这个代码也不行?

点赞
用户179910
用户179910

代码分析

这段代码的基本思路是从文件中读取一行,如果读取成功,则将该行(使用 push_back)添加到结果向量中。重复操作,直到从文件中读取一行失败。然后将所有行的向量返回给调用者。

一些注意事项:尤其是起初,可以相对安全地假设任何指针的使用可能是一个错误。这不应被看作是指针很难使用,或者像那样的任何事情 - 只是它们对于大多数相对初学者在C++中做的事情几乎从不是必要的。

类似于数组 - 起初,假设在其他某些语言中认为的数组相当于C++中的 std::vector。C++确实也有数组,但是使用它们可以等一段时间(在我的意见中可能是很长时间 - 我已经写C++数十年了,几乎从不使用原始指针或数组)。

为了简单起见,我已将数据合并到程序中,因此它从字符串流中读取数据,如下所示:

// 标准头文件
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>

// 命名空间
using namespace std;

// 读取文件函数
vector<string> read_pass(istream &is) {
    string line; // 存储每行数据字符串
    vector<string> lines; // 存储每行数据

    // 循环读取每一行
    while (getline(is, line)) {
        lines.push_back(line); // 将每行数据添加到向量中
    }

    return lines; // 返回所有行数据的向量
}

// 主函数
int main() {
    istringstream input{ "admin\nwhy?\nksfndj" }; // 字符串流
    // 若要从外部文件读取数据,将上一行代码修改为:
    // ifstream input{ "stuff.txt" };

    vector<string> stuff = read_pass(input); // 调用函数,返回所有行数据的向量
    cout << stuff.size() << endl; // 输出行数
    cout << stuff[0] << endl; // 输出第一行数据
    if (stuff[0] == "admin") { // 如果第一行数据是 "admin"
        cout << "true";
    }
    else {
        cout << "false";
    }
    return 0; // 程序正常结束
}

对于我来说,这产生了:

3
admin
true

...表明它已按预期工作。我使用外部文件获得相同结果。如果您在使用外部文件时没有获得相同结果,则我立即猜测(至少是第一行)该文件包含一些您没有预期的数据。如果问题继续存在,您可能考虑以数字格式编写读取的字符串中的各个字符,以便更明确地了解您实际上正在读取什么。

2015-02-21 00:13:31
用户4333718
用户4333718

将长时间研究之后,我终于想出了答案

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <map>

using namespace std;

typedef map<int, string> strArr;

strArr readFile(string file) {
  ifstream stream(file);
  string line;
  strArr output;
  while(getline(stream, line)) {
    output[output.size()+1] = line;
  }
  stream.close();
  return output;
}

该代码不会将文件读入数组,但是它会返回一个类似数组的映射表。

2015-03-23 13:40:04