Read a single line in cpp

Viewed 44

I want to read a single line from a file. My code looks like this:

#include <iostream>
#include <fstream>
#include <string>

#define pause system("pause");
using namespace std;

string entscheidung;

int main()
{
    string s;
    //READ IN CODE FILE 
    cout << "VERZEICHNIS bzw file angeben:";
    cin >> entscheidung;
    char buffer[256];
    ifstream infile;
    infile.open("xxx.in.txt");
    infile.getline(buffer, 256);
        
    return 0;
}

But somehow, it doesn't work, can somebody help me?

1 Answers

To read in a single line of a file:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream my_file("my_text.txt");
    std::string   my_text;
    std::getline(my_file, my_text);

    std::cout << "The text read: " << my_text << "\n";
    return 0;
}

In the above example, the text line is read from a file, by using std::string to receive the text, std::getline to read the text line from the file and ifstream to open the file.

Related