Number of Columns and Rows in Text File

Number of Columns and Rows in Text File

#include
#include
#include
void main()
{
    fstream fptr("kk.txt",ios::in|ios::out);
    char ch;
    int n=0,m=1,row,col;
    clrscr();
    fptr.seekg(0,ios::beg);
    while(!fptr.eof())
    {
        fptr.get(ch);
        if(ch!='\\n')
        {
            if(isdigit(ch))
            {       n=n+1;
                if(!fptr.eof())
                {
                    cout<
4 posts / 0 nouveau(x)
Dernière contribution
Reportez-vous à notre Notice d'optimisation pour plus d'informations sur les choix et l'optimisation des performances dans les produits logiciels Intel.

Hi Safaam,

Conio isn't support on most linux compiler
http://en.wikipedia.org/wiki/Conio.h

I advise you to use ifstream function instead of conio.
Something like this :

#include 
#include 
#include 
#include 
ifstream inputFile("pathToFile");
string currentLine;
short currentShort;
int row = 0, column = 0;
while(!inputFile.eof()){ //Browse each line of the file
    getline(inputFile, currentLine);
    istringstream iss(currentLine);//Parse current line
    while(!iss.eof()){
        iss >> currentShort;
        column++;
    }
    row++;
}

//EDIT
if(column % row) {//error wrong number of column.}
column /= row;

PS : You can use syntaxhighlighter for your code.

Hi watermy,

I found a small error with your code, where the number of columns was not right.

Here is the correct code:

ifstream inputFile("InputFile");  
		string currentLine;  
		short currentShort;  
		int row = 0, column;  
		while(!inputFile.eof())
		{ 
			//Browse each line of the file  
			getline(inputFile, currentLine);  
			istringstream iss(currentLine);//Parse current line  
			column = 0; 
			while(!iss.eof())
			{  
				iss >> currentShort;  
				column++;  
			}  
			row++;  
		}

Nice one sherifhany !
I want to add that it's also not the best way to count the column either.

You can keep my code and retrieve the good column number like this :

column = column / row;

and you can check if there is problem on the file :

if(column % row){
   //Error
}

But the main point of my previous post is not the code but to avoid conio.

Laisser un commentaire

Veuillez ouvrir une session pour ajouter un commentaire. Pas encore membre ? Rejoignez-nous dès aujourd’hui