www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Unexpected ' ' when converting from type string to type int

reply Michael S <mike nameen.com> writes:
Hello,  thanks for stopping in. I am fuddling through some 
exercises on a certain website, and I have come across a very 
frustrating bug I can't seem to fix.

The Problem:
Given a square matrix of size N×N, calculate the absolute 
difference between the sums of its diagonals.

Sample Input:
3
11 2 4
4 5 6
10 8 -12

First line is N, and the expected result of this example is 15.
If I hardcode in the value for N, this code works just peachy. 
It's when I am trying to actually read in the value of the first 
line from stdin that I am having a problem.

I seem to be unable to convert the string input to an integer to 
use later on. The code:

import std.stdio, std.math, std.string, std.conv;

void main(){
     auto matrix_size = readln;

     //below I have commented out the offending call to to!int and 
replaced it with a hardcoded value 3 in order to force it to work.
     auto ms = 3;//matrix_size.to!int;
     int[][] matrix = new int[][ms];
     for(int i = 0; i < ms; i++){
         string[] string_nums = readln.split;
         foreach (num; string_nums){
             auto value = num.to!int;
             matrix[i] ~= value;
         }
     }

     int primary_sum = 0;
     int secondary_sum = 0;
     int j = 0;
     int i = ms - 1;
     //determine diagonal sums
     for(int row = 0; row < ms; ++row){
         primary_sum += matrix[row][j];
         secondary_sum += matrix[row][i];
         ++j;
         --i;
     }
     auto result = abs(primary_sum - secondary_sum);
     result.writeln;
}
Dec 29 2015
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 30 December 2015 at 01:36:56 UTC, Michael S wrote:
     auto matrix_size = readln;
Change that to auto matrix_size = readln.strip; and you should be in business. readln() returns any leading spaces and the newline character at the end of the line too, which is why to is throwing. The .strip function will trim that whitespace off.
Dec 29 2015
parent Michael S <mike nameen.com> writes:
On Wednesday, 30 December 2015 at 01:38:32 UTC, Adam D. Ruppe 
wrote:
 On Wednesday, 30 December 2015 at 01:36:56 UTC, Michael S wrote:
     auto matrix_size = readln;
Change that to auto matrix_size = readln.strip; and you should be in business. readln() returns any leading spaces and the newline character at the end of the line too, which is why to is throwing. The .strip function will trim that whitespace off.
Wow thank you Adam. I didn't expect to have a reply so quickly, especially a slam dunk like that one. It works perfectly now!
Dec 29 2015