Reading variables from a text file in C++
Forgive me if there is another thread like this one but I did not see a thread that matched what I was looking for.
I can read lines from a text file easy but I do not know how to read a single variable and store it to an array. For example: 1 1 1 0 0 0 1 0 0 1 0 1 1 0 0 1 0 0 1 1 1 0 0 1 0 0 I can read the whole thing but I need to store it into a 2d array. I am having problems reading one number at a time. |
Two common ways:
In C: using fscanf (http://www.cplusplus.com/reference/c...cstdio/fscanf/) In C++: using ifstream and >> operator (http://www.cplusplus.com/reference/iostream)/istream/operator%3E%3E/) I advise to use the C++ way since you code in C++. |
Code:
#include <cstring> |
@neonsignal
Could u please simulate ur code for the input given by OP. I found that the contents stored in array are as follows: 1 0 1 0 1 1 0 0 0 0 0 1 1 1 0 1 1 0 0 0 0 0 1 1 1 0 |
Quote:
|
Seems that the problem was due to newline character in file. Modified the code given by neonsignal a little bit and swapped the index checks. Its working now.
int main() { const size_t Sx = 13, Sy = 2; int a[Sx][Sy]; size_t x = 0, y = 0; std::ifstream file("test.dat"); while (file) { file >> a[x][y]; if (++y == Sx) { y = 0; ++x ; file ; //This line is to read the newline char and discard it } } file.close(); return 0; } |
Seems to be a problem with newline char in file. Modified the code posted by neonsignala bit and swapped the indices, now the code is working.
int main() { const size_t Sx = 13, Sy = 2; int a[Sx][Sy]; size_t x = 0, y = 0; std::ifstream file("test.dat"); while (file) { file >> a[x][y]; if (++y == Sx) { y = 0; ++x ; file ; //This line reads and discards the newline character } } file.close(); return 0; } |
That worked perfectly. Thank's
|
All times are GMT -5. The time now is 07:57 AM. |