T
T.Crane
Hi,
I'm new to C++, and I want to open a file, go through it line by line
and pull out specific things on each line. I've written a test bit of
code to try to do this. For some reason what I'm doing doesn't work
-- it returns a runtime error and I don't know why. Obviously there's
something wrong with how I'm interpreting whatever is returned by the
getline function. Does the getline function not return a string? If
it does, why do I have trouble using string class methods
(like .at())? And if it doesn't return a string object, what does it
return and how do I search for a substring and then display it. The
code is below, and then after that is a test file. Any help you can
give me is much appreciated.
thanks!
trevis
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream myFile("test2.dat",ios::in);
if(!myFile)
{
cerr << "File could not be opened.\n";
exit(1);
}
string line;
size_t loc;
string temp;
while(getline(myFile,line)){
cout << line << setw(5) << line.size() << endl;
if(line.size()!=0){
loc = line.find("Az=",0);
temp = line.substr(loc,3);
cout << line << setw(5) << temp << endl;
}
}
myFile.close();
return 0;
}
The file it's supposed to work on (test2.dat) is below:
S/N 1111
06-08-2007, 10:43
Operator: John Doe
PASS
ANGLE: AZ=0, EL=0
RED
0.000000 0.000000 0.000000 0.000000
0.010000 0.000000 0.000000 0.000000
I'm new to C++, and I want to open a file, go through it line by line
and pull out specific things on each line. I've written a test bit of
code to try to do this. For some reason what I'm doing doesn't work
-- it returns a runtime error and I don't know why. Obviously there's
something wrong with how I'm interpreting whatever is returned by the
getline function. Does the getline function not return a string? If
it does, why do I have trouble using string class methods
(like .at())? And if it doesn't return a string object, what does it
return and how do I search for a substring and then display it. The
code is below, and then after that is a test file. Any help you can
give me is much appreciated.
thanks!
trevis
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream myFile("test2.dat",ios::in);
if(!myFile)
{
cerr << "File could not be opened.\n";
exit(1);
}
string line;
size_t loc;
string temp;
while(getline(myFile,line)){
cout << line << setw(5) << line.size() << endl;
if(line.size()!=0){
loc = line.find("Az=",0);
temp = line.substr(loc,3);
cout << line << setw(5) << temp << endl;
}
}
myFile.close();
return 0;
}
The file it's supposed to work on (test2.dat) is below:
S/N 1111
06-08-2007, 10:43
Operator: John Doe
PASS
ANGLE: AZ=0, EL=0
RED
0.000000 0.000000 0.000000 0.000000
0.010000 0.000000 0.000000 0.000000