In: Computer Science
How would I read only the first line of text file into C++
For instance, the first line of a text file is:
5 (space) 5.
I need to read these numbers into a row variable and a column variable. I am just not sure how to do it.
I can only use the #include header. I can't use any other header.
The project mentions using redirected input in Visual Studio for our text file.
Method 1
===================================================
The following code shows how to read an input file using ifstream.
input.txt
--------
5 5
main.cpp
--------
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string filename = "input.txt";
ifstream infile(filename.c_str());
if(infile.fail()){
cout << "ERROR: could not open input file " << filename
<< endl;
return 0;
}
int row, col;
infile >> row >> col;
cout << "Row = " << row << ", Col = " <<
col << endl;
}
output
=====
Row = 5, Col = 5
===================================================
Method 2: Using file redirection (mostly used to avoid retyping
inputs to program)
===================================================
Here you only use file redirection to provide all the inputs to
your program. So you basically avoid typing in again and again.
Your program will only use cin, but due to file redirection,
instead of you typing in when prompted, the values come from the
file.
Once you have a executable program .exe, you use the command (left
arrow is the redirection operator)
executable_file_name < input_filename
input.txt
--------
5 5
main.cpp
=====
#include <iostream>
using namespace std;
int main(){
int row, col;
cout << "Enter row and column values: ";
cin >> row >> col;
cout << "Row = " << row << ", Col = " <<
col << endl;
}
See the below screen shot. You will see I did not type in
values, but the values were read from file redirection.