0

I have an input file like this:

   Virtual   (A) (A) (A) (A) (A) (A) (A) (A) (A) (A) (A) (A)

The electronic state is 1-A.

Alpha  occ. eigenvalues --   -0.26426  -0.26166  -0.25915  -0.25885  
Alpha  occ. eigenvalues --   -0.25284  -0.25172  -0.24273  -0.23559  
Alpha  occ. eigenvalues --   -0.20078  -0.19615  -0.17676  -0.10810  
Alpha virt. eigenvalues --   -0.07062  -0.06520  -0.05969  -0.01767  
Alpha virt. eigenvalues --   -0.01604  -0.00951  -0.00428   0.00041  

I would like to export the first line obtaining first 11 characters " Alpha virt.". How should I do? I code by C++ language as below code, but it cant finish while loop functio. I dont know why, I am a fresher. Please help me. Thank you so much. My C++ code:

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>

#define FILENAME "filelog.txt"

using namespace std;

int main(void) {
    char* line_buf = NULL;
    size_t line_buf_size = 0;
    int line_count = 0;
    string s;
    std::string dongsosanh = " Alpha virt.";
    FILE* fp = fopen(FILENAME, "r");
    getline(&line_buf, &line_buf_size, fp);
    std::string STRR(line_buf, 11);
    do {
        line_count++;
        getline(&line_buf, &line_buf_size, fp);
    } while(STRR.compare(dongsosanh) != 0);
    std::cout << STRR << endl;
    return 0;
}

Thank you so much.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108

2 Answers2

0

You could just do this:

std::ifstream input(FILENAME);
std::string line;

while(std::getline(input, line)) {
    if(line.substr(0, 11) == "Alpha virt.") {
        std::cout << line << endl;
        return 0;
    }
}

EDIT: added the return statement to make sure only the first line starting with 'Alpha virt.' is printed.

Scamtex
  • 181
  • 1
  • 9
0

Many problems with your program:

line_buf - does not have memory allocated, undef behaviour

line_count - is 0, nothing will be red

You are not closing file at the end.

" Alpha virt." - this line will never be found, it has space at the begining.

STRR is never updated after line has been red, endless loop

Working solution:

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>

#define FILENAME "filelog.txt"

using namespace std;

int main(void) {
    const std::string dongsosanh = "Alpha virt.";
    char* line_buf = new char[100];
    size_t line_buf_size = 100;
    int line_count = 0;
    string s;
    FILE* fp = fopen(FILENAME, "r");
    do {
        line_count++;
        getline(&line_buf, &line_buf_size, fp);
        std::cout << line_buf;
    } while(dongsosanh.compare(0, 11, line_buf, 11));
    free(line_buf);
    fclose(fp);
    return 0;
}

This is to show how it works in your case, but you should use vector instead of char* line_buf.

Mateusz Wojtczak
  • 1,621
  • 1
  • 12
  • 28