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 » Fri Aug 25, 2006 10:39 am

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 » Fri Aug 25, 2006 12:03 pm

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 » Fri Aug 25, 2006 12:52 pm

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

User avatar
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Post by Martin Macko » Sat Aug 26, 2006 10:16 pm

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);

User avatar
Zaspire
New poster
Posts: 36
Joined: Sun Apr 23, 2006 2:42 pm
Location: Russia

Post by Zaspire » Mon Aug 28, 2006 10:08 am

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 » Wed Oct 29, 2014 6:37 pm

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++”