reading till delimiter OR \n in c++?

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
how do I read from a file until EITHER newline OR a delimiter of my choice? do I have to write my own function, or is there a builtin that allows multiple delimiters?
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
Check your PM, but I figured this might be usefull to other people too:

You could read larger chunks of the file and use this function to see if your delimiter is in there:


STRSTR(3) Linux Programmer's Manual STRSTR(3)

NAME
strstr - locate a substring

SYNOPSIS
#include <string.h>

char *strstr(const char *haystack, const char *needle);

DESCRIPTION
The strstr() function finds the first occurrence of the substring needle in the string
haystack. The terminating `\0' characters are not compared.

RETURN VALUE
The strstr() function returns a pointer to the beginning of the substring, or NULL if the sub
 

BFG10K

Lifer
Aug 14, 2000
22,709
2,997
126
Use getline which allows you to specify a delimiter. When you either read that delimiter or a newline it'll stop.

Also you don't need to write your own function at all - just have an infinite loop that advances the file pointer and checks for any number of delimiter characters. Two lines of code is all it takes to do this.
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
From the getline man page:


CONFORMING TO
Both getline() and getdelim() are GNU extensions. They are available since libc 4.6.27.


So it appears getline and getdelim are Linux only, or atleast only on any system GNU libc.
 

BFG10K

Lifer
Aug 14, 2000
22,709
2,997
126
Uh, no.

cin.getline() is a standard ANSI C++ library call. I've used it on MacOS, Linux and Windows.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81


<< Use getline which allows you to specify a delimiter. When you either read that delimiter or a newline it'll stop.

Also you don't need to write your own function at all - just have an infinite loop that advances the file pointer and checks for any number of delimiter characters. Two lines of code is all it takes to do this.
>>


i dont think it stopped at the newline when i tried that. probably wrote it wrong ;). anyway, i worked around the problem by restructuring the input file in a more logical way.
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
Uh, no.

cin.getline() is a standard ANSI C++ library call. I've used it on MacOS, Linux and Windows.


He didn't mention C or C++, I assume then that getline in C is a GNU addition not present on all systems.