Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue with string to int conversion in C++
    primarykey
    data
    text
    <p>I have an application where I get a <code>vector&lt;string&gt;</code>. I need to iterate through each element in the vector and see if a value is an integer value.</p> <p>Although the vector represents strings, few of the elements can contain an integer. I need to figure out which of those elements are integers, and if an element is an integer, I need its value. If an element in the vector is a string, then I just ignore it.</p> <p>I tried to use <code>atoi(vector[index].c_str())</code>, but I have an issue with it. <code>atoi</code> returns an integer value if the value contained in the string is an integer. If not, it returns 0</p> <p>So, consider the following:</p> <pre><code>atoi("Shankar") = 0 atoi("0") = 0 </code></pre> <p>and</p> <pre><code>atoi("123") = 123 atoi("123Shankar") = 123 </code></pre> <p>So, how do I distinguish between the above shown cases? If this cannot be achieved using atoi, then what is the alternate solution to this problem?</p> <p>Please assist.</p> <p><strong>EDIT</strong>:</p> <p>I can loop through the string and see if every character is an integer, but that reduces performance, since for m strings with an average of n characters, I need to check m X n times which makes it O(n^2).</p> <p>is there a better way to solve this problem?</p> <p><strong>EDIT2</strong>:</p> <p>Unfortunately, I cannot use any 3rd party library for this and just use STL</p> <p><strong>EDIT3</strong>:</p> <p>In my application, the vector does not contain any negative integers so I am considering Xeo's solution since sstream does not distinguish between "123" and "123Shankar"</p> <p>Thanks everyone for your assistance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload