【发布时间】:2015-04-22 19:09:55
【问题描述】:
在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;
}
这仍然打印错误,最后,它让我相信由于某种原因,ifstream 读取的"admin" 与"admin" 字符串不同。任何解释这是怎么回事?还是这段代码也不起作用?
【问题讨论】:
-
output不会自动调整大小。你在这里output[sizeof(output)+1]所做的事情是未定义的。 -
即使您可以像这样调整数组的大小,
sizeof运算符也会产生数组中的字节数,而不是条目数,因此寻址将是错误的。 -
此外,返回指向分配在堆栈上的数组的指针是一个坏主意,正如 here 所解释的那样。
-
@LeeYi 您的代码对我来说很好,请确保您的输入文件中没有空格,并且它是在与您编译的代码相同的操作系统上创建的。