Friday, November 3, 2023

Handling left over carriage return

Lines in text files created in Windows end with '\r\n'. If you read that text file in Linux with C++ getline(), your line will have a '\r' at the end because in Linux, getline() only gets rid of '\n'. If you have code that reads a certain number of characters and converts it to floating point using std::stod(), you might get std::invalid_argument exception when trying to read multiple values. You can use the following to take care of this problem:

//blog post: https://simulinkforsoftwareengineers.blogspot.com/2023/11/handling-left-over-carriage-return.html
#include <iostream>
#include <string>
bool isCarriageReturn(const char c) {
return c == '\r';
}
int main() {
std::string line = "\r1.2\r4.56";
const uint32_t wordSize = 4; //length of characters in number
for (size_t i = 0; i < line.length(); i += wordSize) {
std::string word = line.substr(i, wordSize);
//std::cout << "Word: " << word;
//Text files created in Windows have line endings of '\r\n'. On Linux, getline() reads up to '\n' which leaves and extra '\r' at the end of line:
if (isCarriageReturn(word.front())) {
//std::cout << "*** here 1\n";
i++;
word = line.substr(i, wordSize);
}
if (isCarriageReturn(word.back())) {
//std::cout << "*** here 2\n";
word.pop_back();
}
double number = std::stod(word);
std::cout << "number: " << number << std::endl;
}
return 0;
}

No comments:

Post a Comment