How do I write it so if I have ifstream file("file.txt") that has rows of characters like
60
REGULAR NONE
GREEN BEGIN
REGULAR NONE
REGULAR NONE
GREEN END
that I can read one line at a time and do whatever I need with it.
How do I write it so if I have ifstream file("file.txt") that has rows of characters like
60
REGULAR NONE
GREEN BEGIN
REGULAR NONE
REGULAR NONE
GREEN END
that I can read one line at a time and do whatever I need with it.
Here a link that will help with explainiations:
http://www.cplusplus.com/doc/tutorial/files.html
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The key here is the getline() function that reads each line at a time. You can use the getline() function to read each line, and you can also specify delimiter (some type of punctuation i.e: ; . , to stop reading that line and to move to the next line). The general syntax for it is getline(cin, s) where "s" is a string type ( http://www.cppreference.com/wiki/string/getline )
Haha, not even a minute before you replied I found that little section both on that website and in my textbook. Thank you for the help though.
The only problem I seem to have with this is it reads the lines as a string. Is there a function in <string> that allows me to convert a string to an integer?
Haha, not even a minute before you replied I found that little section both on that website and in my textbook. Thank you for the help though.
The only problem I seem to have with this is it reads the lines as a string. Is there a function in <string> that allows me to convert a string to an integer?
Not that I know of in the string
library, but you can convert the string to a C-String and use atoi from cstdlib
:
string aString = "12345";
int anInt = atoi (aString.c_str ());
cout << anInt << endl;
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.