1

How to convert string type into integer type in tcl script.like i fetch data from another file and it is string type. I want to increment that number which is string type so how to do it.

1
  • 1
    Check This. You probably will get more information over here Commented Apr 7, 2016 at 9:35

3 Answers 3

6

Tcl basically conceals all types from you; the value is the value regardless of its type, and all types are serializable as strings. It's common to say “everything is a string” and while that's formally inaccurate, the language conspires to make it appear as if it was true. Thus, if it looks like an integer, it is an integer from the perspective of incr (which is definitely the recommended idiomatic method of incrementing).

However, you can use the scan command to enforce integer-ness a bit more. (It's very much like sscanf() in C, if you know that.)

scan $myValue %d myInteger
incr myInteger

If you're going to use scan properly, you probably ought to check the result of it, which is the number of fields successfully scanned.

if {[scan $myValue %d%c myInteger dummy] != 1} {
    error "\"$myValue\" isn't a proper integer"
}
incr myInteger

You can also use string is integer; the -strict option should be used with this, for historical reasons.

if {![string is integer -strict $myValue]} {
    error "\"$myValue\" isn't a proper integer"
}
incr myValue

A lot of people don't bother with any of this and just increment the (variable containing the) value directly. It'll error out with a default error message if it is impossible.

incr myValue

Tcl always tries to tell you what went wrong when a problem occurs, and also where that problem actually was. Do remember to check the errorInfo global variable for a stack trace…

Sign up to request clarification or add additional context in comments.

Comments

3

Ashish has the right answer. I tried to add an example as a comment on his answer but was unable to format it clearly, so I'm adding as a separate answer. Here is an example:

% set val "123"
123
% incr val
124
% puts $val
124
% set val "abc"
abc
% incr val
expected integer but got "abc"
% puts $val
abc
% 

Comments

1

In Tcl everything is string. Read here http://wiki.tcl.tk/3018

If your are using incr to increment, it will interpret the value and if the value is interpreted to be an integer it will be incremented

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.