read efficiently in c++

The forum to report every bug you find or tell us what you'd like to find in UVa OJ

Moderator: Board moderators

Post Reply
seddik11
New poster
Posts: 2
Joined: Sat Apr 25, 2015 6:01 pm

read efficiently in c++

Post by seddik11 » Sun Apr 26, 2015 3:41 pm

hello guys ! what is the best way to read a line from input and split that string into tokens by a delimiter like space ?

predicate
New poster
Posts: 18
Joined: Tue Jun 17, 2014 9:32 pm
Location: Hyderabad, India

Re: read efficiently in c++

Post by predicate » Tue May 26, 2015 6:48 am

I don't know the best way, but one of the ways is to use the getline function in c++ (http://www.cplusplus.com/reference/stri ... g/getline/).
Once you have read the line in a string, you can split it by passing that string to a stringstream and then using the extract ( >> ) operator (http://www.cplusplus.com/reference/istr ... perator>>/

I have attached a code that reads lines of numbers from the input and then ouputs them one by one. Just a demo.

Code: Select all

#include <bits/stdc++.h>
using namespace std;
int main(void) {
  string line;
  while (getline(cin, line)) {
    stringstream ss(line);
    int n;
    while (ss >> n) {
      cout << n << endl;
    }
  }
  return 0;
}

Post Reply

Return to “Bugs and suggestions”