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.

1 Like

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)

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

2 Likes

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;
}
7 Likes

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…

My C++ solution

#include<bits/stdc++.h>

using namespace std;

int main() {

string input;

vector<vector> 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

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

this is what you need;

2 Likes

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.

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.

@divyag2 Can you explain it in c++ ?

It doesn’t work with two digit numbers.
edit:actually it gets stuck at the end (i.e where there is no character at the end).

try this approach

int d;
char c;
while ( c!= '\n'|| c!= EOF)
{
    scanf("%d%c", &d,&c);
    //some process that saves d
}

Iterate through the above while loop as many times as required. ( one iteration is required for each line of input)

I know this is an old question, but I thought I’d add what I figured out since I came across this page looking for the same thing.

Input methods fscanf, scanf, fscanf_s and scanf_s (probably others, idk) all return an integer indicating how many inputs were successfully read. You can use this to tell when you’ve hit the newline character, since the method will fail to read '\n' when it’s looking for integers.

The following code will read one line of integers from a file, printing each as it goes, and stop reading once it hits the end of the line of integers.

...
// set up the file I'm reading from in a pointer called valueFile
int newVal = 0;
int scannedCount = fscan_f(valueFile, "%d", &newVal); // get input, save input count

while (scannedCount != 0) {
      printf("%d\n", newVal);
      scannedCount = fscan_f(valueFile, "%d", &newVal);
}

using python you can simply do it in one line as-
lst_var =[int(lst_var) for lst_var in input().split()]

C++
int t, x;  cin >> t;
while(t--)
{
    while(1)
    {
        cin >> x;
        cout << x << ' ';
        // peek next charcter w/o extracting it
        char ch = cin.peek();
        if(ch == '\n' or ch == EOF)
            break;
    }
    cout << '\n';
}