简体   繁体   English

使用指针读取和写入文件

[英]Using pointers to read and write to a file

I am new to pointers and I have a task to read a 2d array from a file.我是指针的新手,我的任务是从文件中读取二维数组。 I have to use the function which takes in a parameter (char * path).As you can see i am manually typing in which text file i want to open in the code but i think i have to use pointers as it is the parameter in my 'read_from_file' function.我必须使用接受参数(char * path)的函数。正如你所看到的,我正在手动输入我想在代码中打开的文本文件,但我想我必须使用指针,因为它是我的“read_from_file”函数。 I am taking user inputs at command line to see which file they want to read from using the code below.我正在命令行接受用户输入,以查看他们想要使用下面的代码读取哪个文件。 I'm unsure how to use char* argv[] as parameter that will be passed on to my read_from_file(char *path) so that i can read from the file the user stated.我不确定如何使用 char* argv[] 作为将传递给我的 read_from_file(char *path) 的参数,以便我可以从用户声明的文件中读取。 My code for reading from a file works completely fine but i just want some help with the pointers.我从文件中读取的代码完全正常,但我只是想要一些有关指针的帮助。

int main(int argc, char* argv[]){

int read_from_file(char *path){



ifstream infile("file.txt");
string line;

std::vector<std::vector<int> > num;

std::string line;
while (std::getline(infile, line))

{
    std::vector<int> values;
    std::istringstream iss(line);
int value;
while (iss >> value)
{
    values.push_back(value);
}

num.push_back(values);
}
}

If you don't want anything fancy:如果你不想要任何花哨的东西:

// Note: argv[0] is the name of the program itself, 1..n are actual arguments
for (int i = 1; i < argc; ++i) {
  read_from_file(argv[i]);
}

Then you can use that in your function:然后你可以在你的函数中使用它:

std::ifstream infile(path);

Typically in C++ you should specify arguments like this as const char* .通常在 C++ 中,您应该将这样的参数指定为const char*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM