Skip to content

Instantly share code, notes, and snippets.

@PeteBlackerThe3rd
Last active May 6, 2023 23:53
Show Gist options
  • Save PeteBlackerThe3rd/8ab24aa87620625d3b43f58965baf24a to your computer and use it in GitHub Desktop.
Save PeteBlackerThe3rd/8ab24aa87620625d3b43f58965baf24a to your computer and use it in GitHub Desktop.
drop in non-blocking replacement for std::getline
#include <iostream>
bool getline_async(std::istream& is, std::string& str, char delim = '\n') {
static std::string lineSoFar;
char inChar;
int charsRead = 0;
bool lineRead = false;
str = "";
do {
charsRead = is.readsome(&inChar, 1);
if (charsRead == 1) {
// if the delimiter is read then return the string so far
if (inChar == delim) {
str = lineSoFar;
lineSoFar = "";
lineRead = true;
} else { // otherwise add it to the string so far
lineSoFar.append(1, inChar);
}
}
} while (charsRead != 0 && !lineRead);
return lineRead;
}
@PeteBlackerThe3rd
Copy link
Author

doesnt work
Can you describe the issue you're having. I've successfully used this function many times.

@bend-n
Copy link

bend-n commented May 6, 2023

dont remember but i was using it on a embedded system and it was returning garbage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment