Reputation: 39
Needing guidance on how to read numbers from a file and setting each individual number from the rows to set up functions
I have read through the file and was able to print out the numbers onto the screen, but I'm running into some understanding on how am I going to be able to print use on of those numbers for a specific function that I am wanting to use. For instance I have
string line;
while(getline(file,line)){
cout<<line<<"\n";
}
/* What the file is and what it prints out onto the screen
3 6
2 3 2
2 1 6
2 1 4
1 2 3
1 1 2
2 1 8
*/
For instance I want to use the 3 and 6 for a function such as
create_list(int x, int y){}
In other words each set set of numbers in each row will be representing input to some functions
Upvotes: 0
Views: 1119
Reputation: 2660
Parsing variable number of integers from input line
It is not clear from the question what you are trying to do. As mentioned in the comments, you can parse the file directory using the ifstream. I am lazy and always parse files with getline(<ifstream>, str)
and then parse the lines using an istringstream. I make fewer mistakes this way.
One of the questions was why you have multiple line lengths. No matter, I made up functions that were called depending on whether there were 1, 2, or 3 integers for each input line.
The great thing about parsing the input using a stream, is that the stream processor can parse ints, doubles, or whatever.
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
int square(std::vector<int> &ints)
{
return ints[0] * ints[0];
}
int rectangle(std::vector<int> &ints)
{
return ints[0] * ints[1];
}
int volume(std::vector<int> &ints)
{
return ints[0] * ints[1] * ints[2];
}
int main()
{
std::ifstream file;
file.open("example.txt");
std::string str;
while (getline(file, str)) {
int parsed_int;
std::vector<int> ints;
int index = 0;
std::stringstream stream(str);
while (stream >> parsed_int) {
ints.push_back(parsed_int);
++index;
}
int answer = 0;
// index is the number of integers read on this line from the file
switch (index) {
case 0:break;
case 1:answer = square(ints);
break;
case 2:answer = rectangle(ints);
break;
case 3:answer = volume(ints);
break;
default:break;
}
std::cout << "Answer is " << answer << "\n";
}
}
Upvotes: 2