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

Reading from a file

I wrote a little program to read soma data from a *.txt file.
The content of the file is "5 , 10, 15".

The program shall identify the numbers, e.g. "5" and "10" and "15".
This works until the last two numbers. Unfortunately the program doesn't read the last two numbers.

When I set a "," at the end of the file, "5, 10, 15," then it works.

I don't know what the reason for this behaviour is. Maybe someone could help me?

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

using namespace std;

int main()
{
    ifstream filestream("test.txt");
    string s;
    for(char ch;filestream.good();)
    {
        filestream.get(ch);
        if((ch>='0') && (ch<='9'))
        {
            s+=ch;
        }

        else 
        {
          cout<<s<<" ";
          s.clear();
        }
    }

    return 0;
}
Sunshine2011
Newbie Poster
20 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

To me your code seems ok logically. Just a small guess, are you sure you enter a newline in your text file at the end i.e. after 15. If not just give it a try. I am not sure this will work but can't think of anything else at this moment

DJSAN10
Posting Whiz in Training
249 posts since Dec 2010
Reputation Points: 38
Solved Threads: 26
 

No, there is no newline. If I enter a newline at the end of textfile, it works as well as a ",".
But normally reading from a file should also work, when there is no newline or ",", shouldn't it?

Sunshine2011
Newbie Poster
20 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

Here is a stack overflow thread that highlights on this issue
http://stackoverflow.com/questions/729692/why-should-files-end-with-a-newline

and there is 1 from here too.. :) :)
http://www.daniweb.com/software-development/c/threads/7957

DJSAN10
Posting Whiz in Training
249 posts since Dec 2010
Reputation Points: 38
Solved Threads: 26
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You