how I can read until eoln in c++?

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

Moderator: Board moderators

Post Reply
Giorgi
New poster
Posts: 48
Joined: Wed Jun 07, 2006 6:26 pm
Location: Georgia Tbilisi

how I can read until eoln in c++?

Post by Giorgi »

please help to read integer numbers until eoln.

in pascal a do it so:

Code: Select all

var k:integer;
 begin
  while not eoln do 
   begin
    read(k);
    . 
    .
    .
   end;
 end.
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Post by mf »

You can do it with this code:

Code: Select all

int k; char c;
while (scanf("%d%c", &k, &c) == 2 && c != '\n') { ... }
(Of course, this assumes that there are no trailing spaces at the end of line.)
Giorgi
New poster
Posts: 48
Joined: Wed Jun 07, 2006 6:26 pm
Location: Georgia Tbilisi

Post by Giorgi »

mf wrote:You can do it with this code:

Code: Select all

int k; char c;
while (scanf("%d%c", &k, &c) == 2 && c != '\n') { ... }
(Of course, this assumes that there are no trailing spaces at the end of line.)
thank you
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Post by Martin Macko »

mf wrote:(Of course, this assumes that there are no trailing spaces at the end of line.)
You can skip any trailing spaces by "%*[ ]".
........scanf("%d%*[ ]", &a);
........scanf("%c", &c);
Zaspire
New poster
Posts: 36
Joined: Sun Apr 23, 2006 2:42 pm
Location: Russia

Post by Zaspire »

You can simple get line and then use std::istringstream
Zyaad Jaunnoo
Experienced poster
Posts: 122
Joined: Tue Apr 16, 2002 10:07 am

Re: how I can read until eoln in c++?

Post by Zyaad Jaunnoo »

Code: Select all

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

using namespace std;

int main()
{
	string line;
	getline(cin, line);

	stringstream stream(line);

	int k;
	while (stream >> k)
	{
		cout << k << endl;
	}

	return 0;
}
Post Reply

Return to “C++”