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. 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. 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*
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.