Is there a function that returns character / string at point in .txt?
I know it is possible to get the .txt part and then convert it to an integer and then store it in a variable, but is it possible in one declaration. (The variable must be global).
Those:
[data.txt]
1020
[convert_data.cpp]
#include<fstream>
fstream convert("data.txt");
//way to declare something equal to A PARTICULAR POINT in data.txt
int main()
{
//how would I take this block of code and simplify it to two DECLARATIONS (not
//function calls), or, if that not possible or not practical, how would I make
//n and m (or var1 and var2) global AND CONSTANT?
char var1[5];
convert.getline(var1,2);
char var2[5];
convert.getline(var2,2);
const int n=atoi(var1);
const int m=atoi(var2);
return 0;
}
No, you cannot do it in one declaration. You can write a function to do this, and then you can initialize local variables with that function, but you cannot initialize global variables with it. If you want to initialize global variables, you will need to do this explicitly during your program's initialization routine, or you can do this in the constructor of the global object (not recommended).
source to share
From the compiler's point of view, a constant is something that has a fixed value at compile time. Since you are reading data from a text file (which can be changed after the program is compiled), the numbers you read from the text file cannot be constants in your program.
Having said that, you can do something like this:
class ConstInteger {
public:
ConstInteger(fstream &f) {
char s[5];
f.getline(s,2);
value = atoi(s);
}
public operator int() const { return value; }
private:
int value;
};
fstream convert("data.txt");
ConstInteger n(convert);
The above relies on the initialization that the C ++ compiler does for global classes. As a consequence, you are largely at the mercy of the C ++ compiler with respect to the initialization order of the class. Also, error handling in this layout can be problematic. (For example, what happens if it data.txt
doesn't exist?)
source to share
If I understand correctly, you want to read a part of a text file and store the value as a constant? Well, you cannot have an uninitialized constant - the kind of global declaration that you assign at runtime.
Perhaps the way to do this is to encapsulate what functionality you have in a global function called getConstant, this can contain a static variable and the getConstant call checks if var is read from file if it then return a constant if it is not read in file ... Lazy assessment. Of course, this does not solve the question that it should (?) Be constant.
source to share