read line by line from text file to string

Hi.
I have a text file (test.txt) with the following data:
01,05,25,20130728
01,06,25,20130728
01,07,25,20130728
01,08,25,20130728
01,05,25,20130728
01,05,25,20130728
01,05,45,20130728
01,05,65,20130728
01,05,85,20130728
01,05,35,20130728
01,05,25,20130728
01,05,35,20130728

i want to read this to one string called line.

so far i have this code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
string line;
ifstream myfile ("/home/Test.txt");
     if (myfile.is_open())
       {
          while (myfile.good())
	{
	  getline (myfile, line);
        for (int a = 0; a <= 335; a++)
		{
		   cout <<line.at(a);
		}
		 }
	myfile.close();
  }


so far its only printing the first line and then throwing an instance of 'std::out_of_range'
1
2
3
4
5
6
    std::ifstream myfile("/home/Test.txt") ;
    if ( myfile.is_open() )
    {
        while ( std::getline(myfile, line) )
            std::cout << line << '\n' ;
    }


or, if for some reason you're adamant about displaying each character individually via at:

1
2
3
4
5
6
7
8
9
10
    std::ifstream myfile("/home/Test.txt") ;
    if ( myfile.is_open() )
    {
        while ( std::getline(myfile, line) )
        {
            for ( unsigned i=0; i<line.length(); ++i )
               std::cout << line.at(i) ;
            std::cout << '\n' ;
        }
    }

thanks a lot, that code snippet works but it reads everything at once. I am sending the data to a modem and it expects 335 digits at one time. so i am looking for something that will have to read 335 digits from that file each time,
in your code,
for ( unsigned i=0; i<line.length(); ++i )
std::cout << line.at(i) ;

if i put a digit 10, it wont print the whole line...
Topic archived. No new replies allowed.