Home » Extra libraries, Code snippets, applications etc. » C++ language problems and code snippets » Read a text file and assign values to variables int and double
Re: Read a text file and assign values to variables int and double [message #58101 is a reply to message #46495] |
Mon, 14 February 2022 19:35  |
jjacksonRIAB
Messages: 227 Registered: June 2011
|
Experienced Member |
|
|
Very old question and no one answered it but if you want solutions for parsing files a good place to start is with CParser. Yes, it's made to parse C-like languages but it can be adapted for other purposes quite easily.
#include <Core/Core.h>
using namespace Upp;
String test =
R"(
1 ____ 100.00
2 ____ 200.00
3 ____ 300.00
)";
CONSOLE_APP_MAIN {
CParser parser;
parser.Set(test);
Vector<int> integers;
Vector<double> doubles;
while(!parser.IsEof()) {
if(parser.IsNumber()) {
integers.Add() = parser.ReadNumber();
while(parser.IsChar('_')) parser.PassChar('_');
if(parser.IsDouble()) {
doubles.Add() = parser.ReadDouble();
}
}
else {
CParser::Pos pos = parser.GetPos();
Cout() << Format("Error: Unexpected input at (%d, %d)\n", pos.GetColumn(), pos.line);
return;
}
}
Cout() << integers << EOL
<< doubles << EOL;
}
I'm posting this after so long with no answer because even though you may not have received an answer in a timely manner, someone else will at least find this useful.
Forgot to add that passing on '_' is not strictly necessary unless by "blank space" you mean anything instead of whitespace. CParser will, by default, skip whitespace and if you don't care about verifying the parse, you can easily get away with:
CONSOLE_APP_MAIN {
CParser parser;
parser.Set(test);
Vector<int> integers;
Vector<double> doubles;
while(!parser.IsEof()) {
integers.Add() = parser.ReadNumber();
doubles.Add() = parser.ReadDouble();
}
Cout() << integers << EOL
<< doubles << EOL;
}
but I wanted to show off CParser a bit.
[Updated on: Mon, 14 February 2022 19:51] Report message to a moderator
|
|
|
Goto Forum:
Current Time: Tue Jun 17 05:17:59 CEST 2025
Total time taken to generate the page: 0.04668 seconds
|