954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to detect end of line in C++?

Hi!
Please, I really need help with a problem.
I need to read numbers (float type) from a file. Numbers are arranged in rows, I don't know how many in each row, there may be a large number of numbers (milions). How can I read each row of numbers, for example to know how many are in each line?
That's because in C++ there is no eoln function, to detect end of line.
My text file can be:
2.345 1 100.5
23.45 12
11.2 100.2345789 1000 1 1 1
2 3 4 5
1
2
7
If I read every row in a string, I can extract from there every number, but if in a row there are many, many numbers, I have a memory restriction problem, so I can't declare a string char s[100 000 000], maybe bigger, for example.

I wrote this code, but I have some problems (except the problem detailed in rows before):

# include
using namespace std;
long x,i;
long double a;
char s[1000000], *p, b[1000000], d[]=" ";
ifstream f("date.in");
ofstream g("date.out");
int main()
{ do
{ f.get(s,1000000);
f.get();
p=strchr(s,' ');
while (p)
{ i=p-s;
strncpy(b,s,1000000);
b[i]='\n';
a=atof(b);
g<

saanda
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

Presumably each line is processed individually, in which case you can simply read a line at a time and then parse it. As an example, this program would echo the file to stdout:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

int main()
{
  std::ifstream in("file");

  if (in) {
    std::string line;

    while (std::getline(in, line)) {
      // Parse the line using a string stream
      std::istringstream row(line);
      double field;

      while (row>> field)
        std::cout<< field <<'\t';

      std::cout<<'\n';
    }
  }
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

You can try out this. Only you cannot press enter after the ending line.

#include<iostream>
#include<fstream>
using namespce std;

[QUOTE]
int main() {
      int x=0, y=1;
      char ch;
      ifstream in("file.txt");
      while(in.get(ch))
           {
              if (ch!='\n' && isspace(ch))
                   {
                      x++;
                   }
              else if (ch=='\n')
                  {
                     cout<<"Line"<<y<<":"<<x+1<<endl;
                     x=0;
                     y++;
                   }
              }
            return 0;
}
mtbs1826
Light Poster
25 posts since Aug 2010
Reputation Points: 9
Solved Threads: 3
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You