reading multiple text file, char

hi. I need to read text from a file that is written on multiple rows. The problem has more requirements and I have done them buy they didn't work and I'm sure it's because of the reading. I don't know how to use strings yet and i don't have time to learn. can you tell me if this is correct and if it's not then how should I do it?

for example the text file has:
skd dsds 2
sds d 0

and I want s to be "skd dsds 2 sds d 0";

1
2
3
4
5
6
  while(!fin.eof())
{
  fin.getline(row,256);
  strcpy(s+l,row);
  l=strlen(row);
}
Last edited on
I don't know how to use strings yet and i don't have time to learn.
.
Strings are so simple they don't even take time to learn. Have a look at this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This string will hold the result (skd dsds 2 sds d 0)
std::string result;

// Loop through the rows in the file
while ( !fin.eof() )
{
    // During each loop, we will store the row we are at in this string
    std::string row;
    
    // Put the row in that string
    std::getline( fin, row );

    // Add the row to the result string
    result += row;
}
Whether you use std::string (easy) or c-strings (more tricky), the overall logic is similar. But in any case, it's not a good idea to use while(!fin.eof()). The problem there is it checks the state of the file before attempting to read from it, which isn't much use. What you really need to know is, after any attempt at reading from the file, did it succeed or fail.

Example 1 (c-string):
1
2
3
4
5
6
7
8
9
10
11
12
    char row[256];
    char s[4096] = "";
    
    ifstream fin("input.txt");

    while (fin.getline(row, 256))
    {
        strcat(s,row);    // concatenate with existing contents of s
        strcat(s, " ");   // add space
    }

    cout << s << endl;


Example 2 (std::string):
1
2
3
4
5
6
7
8
9
10
11
12
    string row;
    string s;
    
    ifstream fin("input.txt");

    while (getline(fin, row))
    {
        s += row;   // concatenate with existing contents of s
        s += " ";   // add space
    }

    cout << s << endl;
Last edited on
thanks very much both of you :D
Topic archived. No new replies allowed.