c++ - Read from a file different types of variables (1 per line) -
i have app written in c++ gets parameters extern txt file. file has 1 variable per line , they're different kinds like:
0
0.8
c:\documents\textfile.txt
9
i tried (not don't have code now)
file* f; char line[300]; f = fopen("parameters.txt", "r"); scanf(line, val1); scanf(line, val2); scanf(line, val3); fclose(f);
but doesn't work, tried fgets , fgetc changes , didn't work. or idea? variables same number , have same types in each place (so think don't need while or loop). thank in newbie problem driving me crazy.
edit: exact code saw @ solution here
sscanf(line, "%99[^\n]", tp); sscanf(line, "%99[^\n]", mcl); sscanf(line, "%99[^\n]", pmt); sscanf(line, "%99[^\n]", amx);
it didn't work, compiled program crashed changed scanf , didn't crashed variables empty.
since you're using c++ (not c) suggest use standard iostreams library instead of c stdio. in particular, std::ifstream @ reading formatted data file.
#include <fstream> #include <string> // ... std::ifstream f("parameters.txt"); int val1; f >> val1; double val2; f >> val2; std::string val3; std::getline(f, val3); // etc
depending on application, might want error checks well. see http://www.cplusplus.com/reference/iolibrary/ iostream details.
Comments
Post a Comment