how can i get the amount of lines of text does a text file contain?

Hey all,
how can i get the amount of lines of text does a text file contain?
like if say i have a file


XXXXXXX
XXXXX
XXXXXXXXXXXX
XX
XXXXXXXX
XXXXXXX
XXXX

and it would output 7?

becouse i need to have a 2d array of chars, like char array[lines][30] (30 being the maximum number of characters one line could have)
1
2
3
4
std::ifstream ifs("file.txt");
std::string s;
int n = 0;
while(std::getline(ifs, s)) ++n;
Last edited on
what does ifs mean?
It's just the name I gave to a std::ifstream object which allows you to read the file.
oh, didn't notice, thanks :D
What about reading/writing to a specific line in a file?
seekg(position);

EDIT: yo, how can you compare a horizontal string in a 2d array of chars to another string? like:

char array[100][100]

how could you compare
array[100][ from 0 to 100] and "blah"

?
Last edited on
seekg() won't allow you to choose a line. You could use getline() while(n != desired_line). A more efficient way would be to parse character by character and count the newlines, since you don't care for the strings getline() stores anyway:

1
2
3
4
5
6
7
8
std::ifstream ifs("file.txt");
char ch;
int n = 0; // lines are numbered from 0 here
while(n != desired_line && ifs.get(ch))
{
    if(ch == '\n') ++n;
}
// now we can overwrite or read the file at desired_line 
@award982:
You can use nested for loops:
1
2
3
4
5
for (j = 0; j < matrixheight; j++)
    for (i = 0; i < matrixwidth; i++)
    {
         //compare array1[i][j] to array2[i][j]
    }

@filipe:
Thanks, that makes sense.
so lets say i need to have if statments for comparing one line of the 2d matrix to a string i can do it like this?

1
2
3
4
5
6
for (j = 0; j < matrixheight; j++)
    for (i = 0; i < matrixwidth; i++)
    {
  if(array1[i][j] == "xxxxxxx"){
//blah
    }


that will definitely not work, it will just compare one character(lets say array[1][1]) to a string. not good.

Pls tell me how can i compare those, i just can't seem to figure out the placement of the loops, like to get the reverse of

case 'a' : output<<"x0*00x"<<endl;break;

in each loop

like something like case "x0*0x" : output<<"a";break;
Last edited on
If you're comparing strings then you should consider using a string class.
closed account (3pj6b7Xj)
or you could load the file into a vector...

1
2
3
4
5
6
7
8
9
10
11
vector<string> filetext;

string mumblejumble("asdkjfhalskjdfhlaksjhfdlkasjdfhlkasjfhlksjdfhlaksjfhlksahf");

for (int i = 0; i < 1000; i++)
{
     filetext.push_back(mumblejumble);
}

int lines_in_garbage = filetext.size();
Topic archived. No new replies allowed.