Reputation: 55
For example, given "1912" as input, how do I parse this input and populate an int a[]
so that it has a[0]=1
, a[1]=9
and so on.
If done through a for
loop it will take a[0]=1912
and not a[0]=1
.
for(int i=0;i<n;i++){
cin>>a[i];
}
Upvotes: 1
Views: 2255
Reputation: 16737
Use getchar
to read character by character. Your loop would look like this:
for(int i = 0; i < n; i++)
{
a[i] = getchar();
a[i] -= '0';
}
The return value of getchar
would be the ascii code for the input character. Since you are trying to read the input in as a digit, you can do that transformation by a[i] -= '0'
.
Of course, the above loop does not do any input sanitization and assumes you know exactly the format you are reading. You can use feof
and ferror
to get for errors.
Upvotes: 1