I am very new to this and I am having a hard time grasping what I need to be doing. How do I read from a file and determine how many inputs are on a line so that I can do certain actions depending on how many inputs are available on the line?!
I am very new to this and I am having a hard time grasping what I need to be doing. How do I read from a file and determine how many inputs are on a line so that I can do certain actions depending on how many inputs are available on the line?!
Huh?How do I read from a file and determine how many inputs are on a line so that I can do certain actions depending on how many inputs are available on the line?!
Could you maybe give an example of what you are trying to do? (verbally)
Each line of the file has either 1, 2, or 3 dimensions listed on it. If there is 1 dimesnsion, I need to calculate the area of a circle and square.......if 2 dimensions, I need to calculate the area of a rectangle, etc. I know how to do the calculations and output the calculations. I just do not know how to read the file and determine how many dimensions are on the line.
This is one method:
Code:#include <iostream> #include <fstream> using namespace std; int main() { ifstream file_in; file_in.open("input.txt"); int _1; int _2; int _3; char check; file_in >> _1; //Goes first, we assume atleast one is there check = file_in.peek(); //Looks at next char if (check != '/n') //if next char is new line this if statement is skipped { file_in >> _2; check = file_in.peek(); } if (check != '/n') // If same as before but with 3rd char { file_in >> _3; } file_in.close(); cout << _1 << " " << _2 << " " << _3; system("pause"); return 0; }
Here is the input file:
It is clearly not done, it only gets one line.Code:1 2 3
You will want to put it in a loop to get all the lines until end of file.
The peek and the instream ignore spaces, so it works perfect in this case. Each number can be separated by 10 spaces and it will still work the same.
This is not the only method, but fairly easily.
Hopefully it gets you started in the correction direction.
Peek:
http://www.cplusplus.com/ref/iostream/istream/peek.html
It also currently hardcodeed to output all three no matter what, so if you make a input file with just 2 it will have error in the output.
Last edited by Enahs; 10-24-2005 at 10:30 PM.
Thank you!!! That helps immensely, it is just what I needed.