May 31, 2021 at 11:49am UTC
Hi I have a 4 by 4 comma separated txt file named val.txt that looks like
1,2,3,4
2,4,6,4
1,2,7,8
9,3,1,2
for example. I want to read it into an 4 by 4 array and I am struggling to find any starting point.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream infile;
infile.open("val.txt");
if (!infile)
{
cout << "Fail" << endl;
}
else
{
stringstream ss;
ss << infile;
cout << ss.str() << endl;
}
return 0;
}
this was just to see if it would take the values but it didnt work so I am lost.
May 31, 2021 at 12:22pm UTC
Possibly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <fstream>
int main()
{
constexpr size_t arrsz {4};
std::ifstream infile("val.txt" );
if (!infile)
return (std::cout << "Fail\n" ), 1;
int array[arrsz][arrsz] {};
for (size_t r = 0; r < arrsz; ++r)
for (size_t c = 0; c < arrsz; ++c, infile.ignore())
infile >> array[r][c];
for (size_t r = 0; r < arrsz; ++r, std::cout << '\n' )
for (size_t c = 0; c < arrsz; ++c)
std::cout << (c != 0 ? " " : "" ) << array[r][c];
}
1 2 3 4
2 4 6 4
1 2 7 8
9 3 1 2
Last edited on May 31, 2021 at 12:53pm UTC
May 31, 2021 at 12:46pm UTC
Thank you Handy Andy for the tip as I am new to this forum this helps alot.
May 31, 2021 at 12:47pm UTC
Thank you jonnin and seeplus I will try both!
May 31, 2021 at 1:05pm UTC
seeplus what is the function of your line 6 I have never seen that before ?
May 31, 2021 at 1:25pm UTC
constexpr just means that the initialisation of a const is done at compile time if possible - not at runtime.
Jun 1, 2021 at 3:50am UTC
A constexpr variable must be initialised at compile time.
Jun 1, 2021 at 1:54pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int N = 4;
int a[N][N];
ifstream in( "val.txt" );
char comma;
for ( int i = 0; i < N; i++ )
{
in >> a[i][0];
for ( int j = 1; j < N; j++ ) in >> comma >> a[i][j];
}
cout << "Check:\n" ;
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ ) cout << a[i][j] << '\t' ;
cout << '\n' ;
}
}
Check:
1 2 3 4
2 4 6 4
1 2 7 8
9 3 1 2
Last edited on Jun 1, 2021 at 1:55pm UTC