Read File line by line to variable and loop - c++

I have a phone.txt like:
09236235965
09236238566
09238434444
09202645965
09236284567
09236235965
..and so on..
How can I process this data line by line in C++ and add it to a variable.
string phonenum;
I know I have to open the file, but after doing so, what is done to access the next line of the file?
ofstream myfile;
myfile.open ("phone.txt");
and also about the variable, the process will be looped, it will make the phonenum variable the current line its processing from the phone.txt.
Like if the first line is read phonenum is the first line, process everything and loop; now the phonenum is the 2nd line, process everything and loop until the end of the last line of the file.
Please help. I'm really new to C++. Thanks.

Read the comments inline please. They will explain what is going on to assist you in learning how this works (hopefully):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main(int argc, char *argv[])
{
// open the file if present, in read mode.
std::ifstream fs("phone.txt");
if (fs.is_open())
{
// variable used to extract strings one by one.
std::string phonenum;
// extract a string from the input, skipping whitespace
// including newlines, tabs, form-feeds, etc. when this
// no longer works (eof or bad file, take your pick) the
// expression will return false
while (fs >> phonenum)
{
// use your phonenum string here.
std::cout << phonenum << '\n';
}
// close the file.
fs.close();
}
return EXIT_SUCCESS;
}

Simple. First, note that you want an ifstream, not an ofstream. When you're reading from a file, you're using it as input - hence the i in ifstream. You then want to loop, using std::getline to fetch a line from the file and process it:
std::ifstream file("phone.txt");
std::string phonenum;
while (std::getline(file, phonenum)) {
// Process phonenum here
std::cout << phonenum << std::endl; // Print the phone number out, for example
}
The reason why std::getline is the while loop condition is because it checks the status of the stream. If std::getline fails in anyway (at the end of your file, for example), the loop will end.

You can do that :
#include <fstream>
using namespace std;
ifstream input("phone.txt");
for( string line; getline( input, line ); )
{
//code
}

Related

How can I read from a file and sort them by category

I'm trying to read a bunch of words from a file and sort them into what kind of words they are (Nouns, Adjective, Verbs ..etc). For example :
-Nouns;
zyrian
zymurgy
zymosis
zymometer
zymolysis
-Verbs_participle;
zoom in
zoom along
zoom
zonk out
zone
I'm using getline to read until the delimiter ';' but how can I know when it read in a type and when it read in a word?
The function below stop right after "-Nouns;"
int main()
{
map<string,string> data_base;
ifstream source ;
source.open("partitioned_data.txt");
char type [MAX];
char word [MAX];
if(source) //check to make sure we have opened the file
{
source.getline(type,MAX,';');
while( source && !source.eof())//make sure we're not at the end of file
{
source.getline(word,MAX);
cout<<type<<endl;
cout<<word<<endl;
source.getline(type,MAX,';');//read the next line
}
}
source.close();
source.clear();
return 0;
}
I am not fully sure about the format of your input file. But you seem to have a file with lines, and in that, items separated by a semicolon.
Reading this should be done differently.
Please see the following example:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
std::istringstream source{R"(noun;tree
noun;house
verb;build
verb;plant
)"};
int main()
{
std::string type{};
std::string word{};
//ifstream source{"partitioned_data.txt"};
if(source) //check to make sure we have opened the file
{
std::string line{};
while(getline(source,line))//make sure we're not at the end of file
{
size_t pos = line.find(';');
if (pos != std::string::npos) {
type = line.substr(0,pos);
word = line.substr(pos+1);
}
std::cout << type << " --> " << word << '\n';
}
}
return 0;
}
There is no need for open and close statements. The constructor and
destructor of the std::ifstream will do that for us.
Do not check eof in while statement
Do not, and never ever use C-Style arrays like char type [MAX];
Read a line in the while statement and check validity of operation in the while. Then work on the read line later.
Search the ';' in the string, and if found, take out the substrings.
If I would knwo the format of the input file, then I will write an even better example for you.
Since I do not have files on SO, I uses a std::istringstream instead. But there is NO difference compared to a file. Simply delete the std::istringstream and uncomment teh ifstream definition in the source code.

read word to file c++

I want get from user word and put into place in file where is certian word.
I have problem with getline.
In new file I don't have any new line.
When I add Newline to string which I write to file, this line is read two times and writeto file to times (I think that bcoz I saw this newfile)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string contain_of_file,bufor,word,empty=" ",new_line="\n";
string conection;
string::size_type position;
cout<<"Give a word";
cin>>word;
ifstream NewFile;
ofstream Nowy1;
Nowy1.open("tekstpa.txt", ios::app);
NewFile.open("plik1.txt");
while(NewFile.good())
{
getline(NewFile, contain_of_file);
cout<<contain_of_file;
position=contain_of_file.find("Zuzia");
if(position!=string::npos)
{
conection=contain_of_file+empty+word+new_line;
Nowy1<<conection;
}
Nowy1<<contain_of_file;
}
Nowy1.close();
NewFile.close();
cin.get();
return 0;
}
The problem here is not your reading. directly, but about your loop.
Do not loop while (stream.good()) or while (!stream.eof()). This is because the eofbit flag is not set until after you try to read from beyond the file. This means that the loop will iterate one extra time, and you try to read from the file but the std::getline call will fails but you don't notice it and just continue as if nothing happened.
Instead do
while (std::getline(NewFile, contain_of_file)) { ... }
And an unrelated tip: The variable conection is not needed, you can instead do just
Nowy1 << contain_of_file << ' ' << word << '\n';

EOF returning blank line or infinite loop

So I am trying to read from a file named input_file till it reaches the end. I've tried using while (!input_file.eof()) but it goes on for an infinite loop. I looked around on the forum and tried using while (getline(input_file, line)) but that just returns an empty line. I'm not using both getline() and the >> operator like other questions were.
How do I get around this? Here's my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Main program
void CalfFlac(ifstream& input_file) {
string text;
string line;
while (getline(input_file, line)) {
text += line;
}
cout << text << endl;
}
int main() {
ifstream input_file;
input_file.open("calfflac.in");
CalfFlac(input_file);
}
input_file contains a single line Confucius say: Madam, I'm Adam. followed by a carriage return.
Thanks for the help!
PS: I'd prefer if the solution remained simple, as this appears to be a pretty simple problem.
EDIT: Make sure you have the right file name! I tried a bogus file name and it printed a blank line as your describe.
I tried your code with a correct file name and it worked for me
In main add this line:
int main() {
ifstream input_file;
input_file.open("calfflac.in");
if(!input_file)
cout << "File path is wrong!";
CalfFlac(input_file);
}

seekg tellg end of line

I have to read lines from an extern text file and need the 1. character of some lines.
Is there a function, which can tell me, in which line the pointer is and an other function, which can set the pointer to the begin of line x?
I have to jump to lines before and after the current position.
There is no such function i think. You will have to implement this functionality yourself using getline() probably, or scan the file for endline characters (\n) one character at a time and store just the one character after this one.
You may find a vector (vector<size_t> probably) helpful to store the offsets of line starts, this way you might be able to jump in the file in a line-based way. But haven't tried this, so it may not work.
You may ake a look at ifstream to read your file in a stream, then use getline() to get each line in a std::string.
Doing so, you can easily iterate trough the lines and grab the characters you need.
Here is an example (taken from here):
// 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; // Here instead of displaying the string
// you probably want to get the first character, aka. line[0]
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

How do I read a text file from the second line using fstream?

How can I make my std::fstream object start reading a text file from the second line?
Use getline() to read the first line, then begin reading the rest of the stream.
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
...
(Changed to std::getline (thanks dalle.myopenid.com))
You could use the ignore feature of the stream:
ifstream stream("filename.txt");
// Get and drop a line
stream.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
// Get and store a line for processing.
// std::getline() has a third parameter the defaults to '\n' as the line
// delimiter.
std::string line;
std::getline(stream,line);
std::string word;
stream >> word; // Reads one space separated word from the stream.
A common mistake for reading a file:
while( someStream.good() ) // !someStream.eof()
{
getline( someStream, line );
cout << line << endl;
}
This fails because: When reading the last line it does not read the EOF marker. So the stream is still good, but there is no more data left in the stream to read. So the loop is re-entered. std::getline() then attempts to read another line from someStream and fails, but still write a line to std::cout.
Simple solution:
while( someStream ) // Same as someStream.good()
{
getline( someStream, line );
if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true
{
// Only write to cout if the getline did not fail.
cout << line << endl;
}
}
Correct Solution:
while(getline( someStream, line ))
{
// Loop only entered if reading a line from somestream is OK.
// Note: getline() returns a stream reference. This is automatically cast
// to boolean for the test. streams have a cast to bool operator that checks
// good()
cout << line << endl;
}
The more efficient way is ignoring strings with std::istream::ignore
for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){
if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\n'))){
//just skipping the line
} else
return HandleReadingLineError(addressesFile, currLineNumber);
}
HandleReadingLineError is not standart but hand-made, of course.
The first parameter is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit:
Link at cplusplus.com: std::istream::ignore
If you are going to skip a lot of lines you definitely should use it instead of getline: when i needed to skip 100000 lines in my file it took about a second in opposite to 22 seconds with getline.
Call getline() once to throw away the first line
There are other methods, but the problem is this, you don't know how long the first line will be do you? So you can't skip it till you know where that first '\n' is. If however you did know how long the first line was going to be, you could simply seek past it, then begin reading, this would be faster.
So to do it the first way would look something like:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
// Open your file
ifstream someStream( "textFile.txt" );
// Set up a place to store our data read from the file
string line;
// Read and throw away the first line simply by doing
// nothing with it and reading again
getline( someStream, line );
// Now begin your useful code
while( !someStream.eof() ) {
// This will just over write the first line read
getline( someStream, line );
cout << line << endl;
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string textString;
string anotherString;
ifstream textFile;
textFile.open("TextFile.txt");
if (textFile.is_open()) {
while (getline(textFile, textString)){
anotherString = anotherString + textString;
}
}
std::cout << anotherString;
textFile.close();
return 0;
}
this code can read file from your specified line from file but you have to make file in file explorer before hand my file name is "temp" code is given below
https://i.stack.imgur.com/OTrsj.png
hope this can help
You can use ignore function as follow:
fstream dataFile("file.txt");
dataFile.ignore(1, '\n'); // ignore one line
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char buffer[256];
ifstream myfile ("test.txt");
// first line
myfile.getline (buffer,100);
// the rest
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}