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
Read a text file and assign values to variables int and double [message #46495] |
Mon, 16 May 2016 10:41  |
281264
Messages: 272 Registered: June 2010 Location: Spain
|
Experienced Member |
|
|
Hi,
Let's imagine that we have a text file with the following format:
1 ____ 100.00
2 ____ 200.00
3 ____ 300.00
.....
There is blank space (represented by the underscores) between the integer numbers in the first column and the double numbers in the second column. Is there any way of opening such a text file and assigning the values to a U++ Vector<int> and Vector<double> containers? In standard C++ (using C++ streams and operator >>) this is simple but how can it be done using U++ Streams (FileIn)? do I have to overload operator >>? is there any simple way of doing it?
Many thanks,
Javier
|
|
|
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: Mon Apr 28 20:32:57 CEST 2025
Total time taken to generate the page: 0.03700 seconds
|