read from file

Hi, i have a file txt with strings and i want to make a string matrix with text values. I wrote this code but it didn't work, some advices?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include "pch.h"
#include <iostream>
#include<string>
#include<string.h>
#include<fstream>
using namespace std;

ifstream f("a.txt");
//ofstream g("b.txt");

int main()
{
	string a, m[100][50];
	int i = 0, j = 0, k1 = 0, k2 = 0;
	while (!f.eof())
	{
		f >> a;
		//g << a;
		if (a == "\n")
		{
			i++; k1++;
		}
		else
		{
			m[i][j] = a;
			j++; k2++;
		}
	}
	for(i = 0; i < k1; i++)
		for (j = 0; j < k2; j++)
		{
			cout << "m[" << i << "][" << j << "]=";
			cout <<m[i][j] << endl;
		}
	f.close();
	//g.close();
}
Test it with char a, not with string a.
You only want to read one sign.

Edit:
You also have to edit Line 19 to if(a == '\n')
Last edited on
I want to have a string in one position, like m[i][j]="asd", not just one char
"It doesn't work" means what, exactly?

Tell us clearly, completely and precisely what the problem is. Show us any error messages you're getting.

Do not expect us to be able to read your mind, because you will only be disappointed.
Favour vectors over C-style arrays if the size is not known at compile time:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <fstream>
#include <iomanip>

// make one row of the matrix from a line of input
std::vector<std::string> make_row( const std::string& line )
{
    std::istringstream stm(line); // use a stringstream to read from the string

    // https://en.cppreference.com/w/cpp/iterator/istream_iterator
    return { std::istream_iterator<std::string>(stm), std::istream_iterator<std::string>() };
}

// make all rows of the same size
void make_same_size_rows( std::vector< std::vector<std::string> >& matrix )
{
    std::size_t max_size = 0 ;
    for( const auto& row : matrix ) if( max_size < row.size() ) max_size = row.size();

    for( auto& row : matrix ) row.resize(max_size);
}

// return the size of the longest string in the matrix
std::size_t get_max_item_size( std::vector< std::vector<std::string> >& matrix )
{
    std::size_t max_size = 0 ;

    for( const auto& row : matrix )
        for( const auto& str : row ) if( max_size < str.size() ) max_size = str.size();

    return max_size;
}

void print( std::vector< std::vector<std::string> >& matrix )
{
    const std::size_t width = get_max_item_size(matrix) + 2 ;
    for( const auto& row : matrix )
    {
        for( const auto& str : row )
            std::cout << std::setw(width) << '"' + str + '"';
        std::cout << '\n' ;
    }
}

int main()
{
    const std::string file_name = "/tmp/a.txt" ;

    {
        // create a test file.
        // comment out in the actual program where the file is already present
        std::ofstream(file_name) << "In C++, we talk about vectors, rather than arrays.\n"
                                    "Vectors have one important advantage: vectors can be\n"
                                    "resized during the execution of the program.\n"
                                    "Methods push_back and pop_back insert and remove\n"
                                    "(respectively) elements at the end of the vector.\n";
    }

    if( std::ifstream file{file_name} )
    {
        std::vector< std::vector<std::string> > matrix;

        std::string line ;
        while( std::getline(file,line) ) matrix.push_back( make_row(line) );

        make_same_size_rows(matrix);

        print(matrix) ;
    }
}

http://coliru.stacked-crooked.com/a/8dd6aaafb752b983
Hello bogdyby,

You wanted some advice so here it is.

When posting your code leave out the line #include "pch.h" . Some people will complain about it and most people can not use it because they are using a different IDE. Even though I use VS2017 I do not use this file as I create empty projects to work with and this file is not needed.

using namespace std; // <--- Best not to use .

An aletrnative would be:
1
2
3
using std::cout;  // <--- Better choice.
using std::cin;
using std::endl;


Line 8. Use better variable names. "f" may seam easy to type and you know what it is, but others find it hard to follow. I like to use "outFile" or even "fOut" is better.

The same is true for your other variables.

Line 15. while (!f.eof())

I do not know why people teach this. This is a bad idea as it does not work the way you think it
will. Generally by the time the while condition determines that "eof" has been reached you will
have processed the last read twice and wondering why it shows up twice.

What happens is the while condition is checked and “eof” has not been set yet. After entering the
while loop you read the last line or bit of information from the file process the information
reach the bottom of the while loop. At this point “eof” has not been set yet and you return to the
while condition which is still good. After entering the loop you try to read from the file, but
now there is nothing left to read and “eof” is set, but you do nothing at this point to deal with
the “eof” condition. So you process what information is in the variables from the last read before
returning to the while condition where it finally detects the “eof”, but you have processed the
last good read twice unless you have cleared the variables at the end of the while loop in which
case the last process will be blank.

A more acceptable way of using the while loop is:
1
2
3
4
5
while (infile >> someVariable)
{
    infile >> additionalVariables;
    //  Additional code.
}
In the above example you can set up the while condition to read one variable, two or more
variables or use “std::getline(?, str)” where ? could be from “std::cin” or from a file stream
and “str” represents any “std::string” variable.



After that I can not tell if the rest of the while is working without an input file to use.

Your for loops look right and you close the file stream before the program ends.

Although the return 0; at the end of "main" is not a requirement it is good form and can be useful as a break point in the IDE when testing.

Your program uses an input file. It would be nice if you include this file in a post or at least a fair sample so everyone is working with the same information.

Hope that helps,

Andy
Thanks for advices guys.
Topic archived. No new replies allowed.