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
atoiis 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 useatoi(oratofor anything fromato...group) in real-life programs. It is practically useless.To perform string-to-number conversions use
strtol(and other functions fromstrto...group).Now, what is inside your
numat the moment you call youratoi? Is yournumproperly zero-terminated?