Hey I am trying to find very basic code to simply open a file which I have created and display the information within it, all this is being done on a win32 console.
ifstream file("[path\\]filename.txt");//open the file for reading
char g;
while (true)
{
file.get(g);//get the next character of the file
if (file.eof()) break;//stop if the end of the file is reached
cout << g;//display the character
}
When you want to get the line
(replace cin >> name with getline )
getline works as the istream >> operator but it reads until the next '\n' character (or any given character) instead of breaking input at the first whitespace
You posted some code with cin >> name ( http://www.cplusplus.com/forum/beginner/8386/#msg38791 ) so I presumed you wanted to get a line there. cin >> name reads some text from the console as getline(cin,name) would do (they differ on when they stop reading)
But if you want to read from a file you should use the an ifstream ( file in the example I provided ) instead of cin
Maybe this code explains better how to use getline:
1 2 3 4 5 6 7
ifstream file("aFile.txt");
string line;
while (!file.eof())
{
getline( file, line );//stores a line in 'line'
cout << line << "\n\n"; //display the line and go newline twice
}
this example will read the lines from the file aFile.txt and display them separed by a blank line
void main ()
{
ifstream file("names.txt");
string line;
//while (!file.eof())
{
getline( file, line );//stores a line in 'line'
cout << line << "\n\n"; //display the line and go newline twice
}
system("pause");
}
I now need to be able to direct to a single line or character, say show property 12 or asomething like that, so far I have been trying for just over a week and it's killing me!!!
ifstream file("File.txt");
string line;
string lookfor = "Property 12";
while (!file.eof())
{
getline( file, line ); // get the line
if ( line.substr(0,lookfor.length()) == lookfor ) // if the line starts with "Property 12"
cout << line.substr(lookfor.length()) << '\n';//Display the rest of the line
}
This will display all the lines starting with "Property 12"
if you want to extract integers from the result ( " 260 30 4" ) you can use stringstreams:
1 2 3 4 5 6 7
if ( line.substr(0,lookfor.length()) == lookfor )
{
stringstream ss(line.substr(lookfor.length()));
int a, b, c;
ss >> a >> b >> c;
cout << "1st value = " << a << "\n2nd value = " << b << "\n3rd value = " << c;
}