• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

reading till delimiter OR \n in c++?

CTho9305

Elite Member
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?
 
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
 
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.
 
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.
 


<< 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.
 
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.
 
Back
Top