You are not logged in. Please login at www.codechef.com to post your questions!

×

How to scan integers until newline?

Is there a simpler way than taking the whole string as input and then separating all of them? Have been searching for a while and can't find a shorter way. I have T lines and they can have any number of values. These values can be negative also. Thanks.

asked 31 Jul '15, 00:55

h1ashdr%40gon's gravatar image

3★h1ashdr@gon
2912319
accept rate: 10%

edited 31 Jul '15, 02:32


I have also been looking for the answer for a while now. Earlier, I did not think properly because people gave hints to use dynamic memory allocation for array. But Actually, it can be done just with a simple do-while loop. code:

#include <stdio.h>
int main(void) {
    int i=0,size,arr[10000];
    char temp; 
    do{
        scanf("%d%c", &arr[i], &temp); 
        i++; 
        } while(temp!= '\n');

    size=i; 
    for(i=0;i<size;i++){ 
        printf("%d ",arr[i]); 
    } 
return 0;
}
link

answered 17 Jun '16, 00:32

divyag2's gravatar image

2★divyag2
4912
accept rate: 0%

edited 24 Feb '17, 12:48

@divyag2 Can you explain it in c++ ?

(17 Jun '16, 11:46) pankaj_chopra4★

One way is to read input character-by-character instead of storing the whole string.

You start storing the input into a number. When you encounter a space, you move to a next number. When you encounter a newline ('\n') or you reach end of input, you stop.

Here is the implementation which reads lines of input into an array and then displays the array.

#include<stdio.h>

int main()
{
    int t,i,a[100],n,num;
    /*I'm assuming that there are max 100 integers per line
    variable i will store the number of integers read successfully so far*/
    char ch,sign;
    scanf("%d",&t);
    getchar();
    /*here getchar() will clears out the '\n' in the input buffer
    which was left out while reading t*/
    while(t--)
    {
        i=0;num=0;sign='+';
        while(scanf("%c",&ch)==1)
        {
            if(ch=='-')sign='-';
            else if(ch==' ' || ch=='\n')
            {
                if(sign=='-')
                {num=-num;sign='+';}
                a[i++] = num;
                num=0;
                if(ch=='\n')break;
            }
            else num = 10*num + (ch-'0');
        }
        n=i;
        /*now we have successfully stored all numbers in a
        and the number of numbers in n*/
        for(i=0;i < n;++i)
            printf("%d ",a[i]);
        putchar('\n');
    }
    return 0;
}

This is the best I could do. I don't know a shorter way to do it. This code is also not resistant to buggy input (like multiple minus signs in a single number, alphabets instead of numeric digits, etc)

link

answered 31 Jul '15, 03:12

sharmaeklavya2's gravatar image

5★sharmaeklavya2
139238
accept rate: 0%

edited 31 Jul '15, 03:43

Yeah that's one day of dealing with it. I guess I'll stick to raw_input().split(' '). Python is better to use in this question I suppose.

(31 Jul '15, 13:41) h1ashdr@gon3★

If you are scanning integers, you could do this way

int n;
while((scanf("%d",&n)) != EOF)
{
    printf("%d",n);
    //other operations with n..
}

Sample code

link

answered 31 Jul '15, 13:30

vinayawsm's gravatar image

4★vinayawsm
1.9k21430
accept rate: 24%

Your code is fine but I want to distinguish between the entries of all the lines. Suppose there are 2 lines. First line with variable number of inputs corresponds to list x and I want to do some operation on x and similarly a different operation on list y.

(31 Jul '15, 13:40) h1ashdr@gon3★

This code is written on c language and can scan for any number of lines and can take max of 100 entries per line..

# include <stdio.h>
 int main(void)
 {
   int get_number[][100],ety_per_row;//first index denote number of lines and second index denotes number of entries per row
   char character_status;
   for(int line=0;(character_status!='e'||character_status!='E')&&(ety_per_row<100);ent_per_row++){
      scanf("%d",&get_number[line][ety_per_row)]);
      if(get_number[line][ety_per_row]=='\n') {line++;ety_per_row=0;}
      character_status=get_number[line][ety_per_row];
    }
}

Since I typed this on cell phone I put maximum effort to eliminate errors..

link
This answer is marked "community wiki".

answered 17 Jun '16, 12:37

chandru58's gravatar image

0★chandru58
1
accept rate: 0%

My C++ solution

include<bits stdc++.h="">

using namespace std;

int main() {

string input;

vector<vector<int>> v; //Vector containing all integers of all lines scanned

int j=1;

while(getline(cin,input)) {

 stringstream x(input);

 vector<int> vt;    //Parsing integers scanned in current line

 int n;

 cout<<"\nLine "<<j<<" scanned: ";

 while(x>>n)
 {

cout<<n<<" ";

vt.push_back(n);

 }

 cout<<endl;

   v.push_back(vt);

j++; } }

Hope it helps

link

answered 24 Feb '17, 13:16

inovation123's gravatar image

4★inovation123
4537
accept rate: 10%

edited 24 Feb '17, 13:19

for(i=0;i<10;i++) { scanf("%d%c",&j[i],&c); if(c=='\n') break; }

this is what you need;

link

answered 19 Jan '18, 02:44

victorpunkd's gravatar image

2★victorpunkd
1
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×40
×39
×2

question asked: 31 Jul '15, 00:55

question was seen: 30,364 times

last updated: 19 Jan '18, 09:14