0

I am trying to understand how reading from a file using ifstream in C++ can be modified to work as needed. Right now, from my understanding, a single string is read if I use an std::string, where the definition of a string is text delimited by whitespace.

So this would read the work "this" into my std::string.

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

int main() {
    std::string fname("file.txt");
    std::string data;

    std::ifstream myfile(fname);

    myfile >> data;

    myfile.close();

    std::cout << "read from file: " << data << std::endl;

    exit(0);
}

If file.txt contained the line "this is a string".

What I am wondering, and cannot find, is if I can modify the behaviour of the >> operator, or possibly overload it in a custom class, to change the delimiter. For example, I could read an entire line until a \n is found. I could read delimiting by commas in a CSV file.

Etc.

Is this possible? I'm used to working in C and Python, and my C++ is rather weak.

Thanks.

Michael Soulier
  • 803
  • 1
  • 9
  • 20
  • 6
    You're looking for [std::getline](https://en.cppreference.com/w/cpp/string/basic_string/getline). Although be careful, because `getline` and `operator>>` don't intermix very nicely and some care is required if you need to use both. – Nathan Pierson Jul 31 '22 at 19:19
  • C++ has functions to read one character at a time, and to put back (at least) one character into the input stream. So if you have particular requirements you can always write your own reading function. But in this case just use `getline` – john Jul 31 '22 at 19:33
  • Reading a CSV file can be more complicated than just reading strings delimited by commas. For instance, if those commas are inside strings surrounded by quotes. There are plenty of questions on StackOverflow related to reading CSV files, and there are actual libraries available for this very purpose. – Remy Lebeau Jul 31 '22 at 20:25
  • Minor point: you don't need to call `myfile.close();`. The destructor will do that. – Pete Becker Jul 31 '22 at 21:07
  • Does this help? https://stackoverflow.com/questions/4197697/c-ifstream-function-and-field-separators – lorro Jul 31 '22 at 21:34
  • If you REALLY need to change the delimiters for cin there is this: https://stackoverflow.com/questions/7302996/changing-the-delimiter-for-cin-c - you can just remove space from the list of whitespace characters. – Jerry Jeremiah Jul 31 '22 at 21:53

0 Answers0