How to get data from text file in C++?

In summary, the code can read data, but it does not know how to scan every single line to get any information it wants.
  • #1
Nate Duong
126
3
Hi Group,

I am trying to get data from text file, I hope someone can suggest me how to do?

I also have this code which can read data, but i do not know how to scan every single line to get any information I want.

Please help, Thank you very much.

Here is my code:
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <boost/lexical_cast.hpp> // convert number to string
using namespace std;int main ()
{
       string input  = "test1.txt";

       string line;

       ifstream fin(input.c_str());

       if (fin.is_open())
       {
/*           while ( getline (fin, line) )
           {
               cout << line << '\n';
           }*/
           while (! fin.eof() )
           {
               getline (fin,line);
               cout << line << endl;
           }

           fin.close();
       }

       else cout << "System can not read the input file, check it again.";
   }

   cout << "Done!" << endl;
    return 0;
}
and the file is attached:

#cP2016 10 12 0 0 0.00000000 96 ORBIT IGb08 HLM IGS
## 1918 259200.00000000 900.00000000 57673 0.0000000000000
+ 32 G01G02G03G04G05G06G07G08G09G10G11G12G13G14G15G16G17
+ G18G19G20G21G22G23G24G25G26G27G28G29G30G31G32 0 0
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
++ 2 2 2 0 2 2 2 2 2 2 2 3 2 2 2 2 2
++ 2 3 2 2 2 2 2 2 2 2 3 3 2 2 2 0 0
++ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
++ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
++ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
%c G cc GPS ccc cccc cccc cccc cccc ccccc ccccc ccccc ccccc
%c cc cc ccc ccc cccc cccc cccc cccc ccccc ccccc ccccc ccccc
%f 1.2500000 1.025000000 0.00000000000 0.000000000000000
%f 0.0000000 0.000000000 0.00000000000 0.000000000000000
%i 0 0 0 0 0 0 0 0 0
%i 0 0 0 0 0 0 0 0 0
/* RAPID ORBIT COMBINATION FROM WEIGHTED AVERAGE OF:
/* cod emr esa gfz jpl ngs sio usn whu
/* REFERENCED TO IGS TIME (IGST) AND TO WEIGHTED MEAN POLE:
/* PCV:IGS08_1915 OL/AL:FES2004 NONE Y ORB:CMB CLK:CMB
* 2016 10 12 0 0 0.00000000
PG01 -13708.647442 10773.249185 19862.568314 36.889073 5 6 6 115
PG02 13719.486776 13609.232181 -17921.238464 541.110472 10 9 8 125
PG03 -23066.347494 13143.568797 580.431793 -92.017995 7 6 8 141[/code]
 

Attachments

  • test1.txt
    1.6 KB · Views: 503
Last edited:
Technology news on Phys.org
  • #2
You can put code in [code]...[/code] tags to keep indentation and other formatting.

You want to work with "line"? You can look for whitespace in its characters and split by that. It is ugly, but possible and you can hide it in some functions that you don't have to touch again later.
There are also tools that can do that for you and split it in separate strings.

There are formats that would be easier to read in.
 
  • Like
Likes Nate Duong
  • #3
mfb said:
You can put code in [code]...[/code] tags to keep indentation and other formatting.

You want to work with "line"? You can look for whitespace in its characters and split by that. It is ugly, but possible and you can hide it in some functions that you don't have to touch again later.
There are also tools that can do that for you and split it in separate strings.

There are formats that would be easier to read in.
@mfb : I am going to scan every single line, such as: PG01 -13708.647442 10773.249185 19862.568314 36.889073 5 6 6 115, They will separate by "space". Any tool can help me to get this done? Thank you.
 
  • #4
How about excel "Text to columns" on the "Data" tab (for selected rows, of course) :smile: ?
 
  • #5
Looks like a CSV with spaces in place of commas.

Here is code that will load a text file into either a buffer or a vector for you.
C:
char * loadToMemory(const char * p_filename){
    FILE * f = fopen(p_filename, "rb");
    if (!f) return NULL;
    if (fseek(f, 0, SEEK_END)){
        fclose(f);
        return NULL;
    }
    long siz;
  
    siz = ftell(f);
    if (siz < 0){
        fclose(f);
        return NULL;
    }
    if (fseek(f, 0, SEEK_SET)){
        fclose(f);
        return NULL;
    }

    char * result = static_cast<char*>(malloc((siz + 1) * sizeof(char)));
    if (!result){  //Out of memory?
        fclose(f);
        return NULL;
    }
    if (static_cast<size_t>(siz) != fread(result, sizeof(char), siz, f)){
        free(result);
        fclose(f);
        return NULL;
    }
    fclose(f);
    result[siz] = '\0';
    return result;
}

bool loadToVector(const char * p_filename, std::vector<std::string> & p_vector) {
    if (char * c_result = loadToMemory(p_filename)){
        if (!*c_result) return false;  //Empty string
        char * stringStart = c_result;
        char * stringEnd = stringStart;
        while(*stringEnd){
            if (*stringEnd == '\n'){
                p_vector.push_back(std::string(stringStart, stringEnd - stringStart));
                stringStart = stringEnd + 1;
            }
            ++stringEnd;
        }
        p_vector.push_back(std::string(stringStart));
        free(c_result);
        return true;
    }
    return false;
}
 
  • Like
Likes Nate Duong
  • #6
newjerseyrunner said:
Looks like a CSV with spaces in place of commas.

Here is code that will load a text file into either a buffer or a vector for you.
C:
char * loadToMemory(const char * p_filename){
    FILE * f = fopen(p_filename, "rb");
    if (!f) return NULL;
    if (fseek(f, 0, SEEK_END)){
        fclose(f);
        return NULL;
    }
    long siz;
 
    siz = ftell(f);
    if (siz < 0){
        fclose(f);
        return NULL;
    }
    if (fseek(f, 0, SEEK_SET)){
        fclose(f);
        return NULL;
    }

    char * result = static_cast<char*>(malloc((siz + 1) * sizeof(char)));
    if (!result){  //Out of memory?
        fclose(f);
        return NULL;
    }
    if (static_cast<size_t>(siz) != fread(result, sizeof(char), siz, f)){
        free(result);
        fclose(f);
        return NULL;
    }
    fclose(f);
    result[siz] = '\0';
    return result;
}

bool loadToVector(const char * p_filename, std::vector<std::string> & p_vector) {
    if (char * c_result = loadToMemory(p_filename)){
        if (!*c_result) return false;  //Empty string
        char * stringStart = c_result;
        char * stringEnd = stringStart;
        while(*stringEnd){
            if (*stringEnd == '\n'){
                p_vector.push_back(std::string(stringStart, stringEnd - stringStart));
                stringStart = stringEnd + 1;
            }
            ++stringEnd;
        }
        p_vector.push_back(std::string(stringStart));
        free(c_result);
        return true;
    }
    return false;
}
Thank you very much, it's really worked.
 
  • Like
Likes newjerseyrunner
  • #7
No problem, as you go along in your career, you'll end up with modules you just bring with you everywhere.
 
  • Like
Likes BvU

Related to How to get data from text file in C++?

1. How do I open and read a text file in C++?

To open and read a text file in C++, you need to use the fstream library. First, declare an ifstream object and pass the name of the text file as a parameter. Then, use a while loop to read the file line by line and store the data into a variable or a data structure.

2. How do I check if a text file exists in C++?

You can use the ifstream object to check if a text file exists in C++. Declare an ifstream object and pass the name of the file as a parameter. Then, use the is_open() function to check if the file is open. If the file exists, the function will return true; otherwise, it will return false.

3. How do I extract data from a specific line in a text file in C++?

You can use the getline() function to extract data from a specific line in a text file. This function takes two parameters - the ifstream object and a string variable. The string variable will store the data from the specified line. You can also use a counter variable to keep track of the line number and extract data from a specific line using if statements within a while loop.

4. How do I convert data from a text file into a specific data type in C++?

You can use the stringstream class to convert data from a text file into a specific data type in C++. First, use the getline() function to extract the data from the file into a string variable. Then, declare a stringstream object and pass the string variable as a parameter. Finally, use the >> operator to extract the data into a variable of the desired data type.

5. How do I handle errors when getting data from a text file in C++?

You can use try-catch blocks to handle errors when getting data from a text file in C++. Wrap your code for reading the file in a try block and use a catch block to handle any errors that may occur, such as the file not existing or data type conversion errors. You can also use the fail() function to check for any errors that may have occurred during the reading process.

Similar threads

  • Programming and Computer Science
Replies
12
Views
2K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
6
Views
970
  • Programming and Computer Science
Replies
34
Views
3K
  • Programming and Computer Science
Replies
6
Views
9K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
1
Views
718
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
Replies
4
Views
5K
  • Programming and Computer Science
4
Replies
118
Views
7K
Back
Top