Reading a file line by line into a variable and loop

I have 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 that I need to open the file, but after that, 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 of its processing from phone.txt.

As if the first line is being read by phonenum - the first line, processes everything and the loop; now phonenum is the second line, processes everything and cyclically to the end of the last line of the file.

Please, help. I am really new to C ++. Thanks.

+4
source share
3 answers

Read the comments in line, please. They will explain what happens to help you find out how it works (hopefully):

 #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char *argv[]) { // open the file if present, in read-text-mode. ifstream fs("phone.txt"); // variable used to extract strings one by one. 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. cout << phonenum << endl; } // close the file on the chance you actually opened it. fs.close(); return EXIT_SUCCESS; } 
+4
source

Simple First, note that you want ifstream , not ofstream . When you read a file, you use it as input - hence, i in ifstream . Then you want to execute the loop using std::getline to extract the 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 std::getline is a condition of the while loop is because it checks the state of the stream. If std::getline fails (at the end of your file, for example), the loop will end.

+3
source

You can do it:

  #include <fstream> using namespace std; ifstream input("phone.txt"); for( string line; getline( input, line ); ) { //code } 
+1
source

Source: https://habr.com/ru/post/1448000/


All Articles