I am trying trying to read in a file in C++ where the characters are separated by bars "|", what is the best way to do that?
Thanks
I am trying trying to read in a file in C++ where the characters are separated by bars "|", what is the best way to do that?
Thanks
I assume that fields are separated by bars, but records are separated by newlines.
First, read in the lines of text using std::getline
:
std::string line;
std::getline(std::cin, line);
Then, break the line at |
boudaries.
std::stringstream sline(line);
std::string field;
std::getline(sline, field, '|');
...
std::getline(sline, field, '|');
Depending on the complexity of the code you're using, what you're looking for is a variation on a CSV (comma seperated value) file reader. There are thousands out there and if your code needs to be robust I'd suggest you use one of them rather than writing your own as there are complexities such as:
One of the most popular is the Boost tokeniser which should be pretty easy to get up and working with. You just need to ensure that you tell the tokeniser that you're using a '|' as a field seperator.
Take a look at this related question for some more pointers.
Assume you have a file called "file.dat"
It looks like this:
item1|item2|item3|item4|item5|item6
This program will print each item in the file:
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
int main(){
std::ifstream infile("file.dat");
std::string item;
getline(infile,item,'|');
while (!infile.eof()){
std::cout << item << std::endl;
getline(infile,item,'|');
}
return EXIT_SUCCESS;
}