read til the end of line

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
zero_cool
New poster
Posts: 27
Joined: Fri Sep 02, 2005 6:33 am

read til the end of line

Post by zero_cool » Mon Sep 12, 2005 7:25 am

does anyone know how to read data from file until the end of line in c++?

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Mon Sep 12, 2005 8:21 am

Code: Select all

while(true){
    sometype val;
    cin >> val;
    if(! cin)break;
}

misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Re: read til the end of line

Post by misof » Mon Sep 12, 2005 8:49 am

zero_cool wrote:does anyone know how to read data from file until the end of line in c++?
Actually, Krzysztof probably misread your question, his code reads data until the end of file. The most-C++ way of reading data until the end of line is probably the following one:

Code: Select all

string S;
getline(cin,S);
stringstream sin(S);
while (sin >> S) cout << "Next token: " << S << endl;

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Mon Sep 12, 2005 10:21 am

Right, sorry. 9 AM is too early for me :-)

zero_cool
New poster
Posts: 27
Joined: Fri Sep 02, 2005 6:33 am

Post by zero_cool » Mon Sep 12, 2005 6:54 pm

thx. that was a great help.

zero_cool
New poster
Posts: 27
Joined: Fri Sep 02, 2005 6:33 am

Post by zero_cool » Mon Sep 12, 2005 11:09 pm

does anyone know how to read til the end of line without using string???

Project
New poster
Posts: 12
Joined: Tue Jul 19, 2005 9:29 am

Post by Project » Sun Sep 18, 2005 4:28 pm

zero_cool wrote:does anyone know how to read til the end of line without using string???
I've seen something like that on this board. There was something with cin.peek ...

lbfacci
New poster
Posts: 4
Joined: Wed Nov 02, 2005 7:28 pm

Post by lbfacci » Tue Nov 08, 2005 4:00 am

I do something like

Code: Select all

int a, b;
char c;

scanf("%d%c", &a, &c);
while(c != '\n' && b == 2)
	b = scanf("%d%c", &a, &c);
But you have to be sure that there is no trailing spaces (usually there arent).

Post Reply

Return to “C++”