-3

I am writing a program in which stdin is read into a buffer, then processed. The vast majority of these items that need to be processed are strings (or well, character arrays). However, I do have one item that needs to be read in as a character array and then converted to int for ease of use in the future.

for(i=0; i<n; i++){
    num[i] = buff[(i)];
    printf("%c", num[i]);
}

convert = atoi(num);

So I know for sure that the correct group of characters is being read into num because the printf for that is correct. However, when I try to print convert I end up getting 0, and I'm very perplexed as to what I'm doing wrong. I know that the 0 return means that a valid conversion could not be performed, but I don't know what's making it invalid. Any tips?

EDIT: Sorry for not including these before >_<

n is the number of chars in the buff array buff is the buffer array stdin is read into

1 Answers1

4

atoi is a function that gives you no means to analyze error conditions. On top of that, it produces undefined behavior in overflow situations. Don't ever use atoi (or atof or anything from ato... group) in real-life programs. It is practically useless.

To perform string-to-number conversions use strtol (and other functions from strto... group).

Now, what is inside your num at the moment you call your atoi? Is your num properly zero-terminated?

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • If `n` is equal to `strlen(buff)` then they likely haven't copied the `NUL` terminator and `strtol` will also report an error. – user7116 Nov 16 '12 at 17:33
  • What does `printf("%s\n", num);` look like? – user7116 Nov 16 '12 at 17:34
  • 2
    @Austin Leigh: Strings in C have to be *zero terminated*. You need **seven** characters to represent string `303502` - six digits and `\0` at the end. – AnT stands with Russia Nov 16 '12 at 17:34
  • so I manually set num(i+1) = '\0' to be sure, but the error still occurs. Additionally, from the documentation suggested below, atoi should terminate at the \n character because it is non-numerical. Is it possible that there is a character that isn't being printed that's messing up the performance? – Austin Leigh Nov 16 '12 at 17:46
  • @Austin Leigh: If you want to zero-terminate your string after the above cycle, you have to set `num[i] = '\0'`. `num[i]`, not `num[i + 1]`. Or better just set `num[n] = '\0'` – AnT stands with Russia Nov 16 '12 at 17:48
  • yep that was the problem - I thought it was copying the \0 over but it wasn't. Thanks a lot; I'm just learning C strings and I keep missing silly things like that >_ – Austin Leigh Nov 16 '12 at 18:08