atoi() returning 0 from char array [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
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

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?

Related

Would you please explain why I am getting error in this testcase 99? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
https://codeforces.com/contest/61/problem/A
Here in the testcase 99 of this I am experiencing an error which I am not getting in codeblocks. What I have identified is, after printing the needed output correctly, some 1s are being printed. I am not getting the fact why these 1s are being printed.
Here is my code:
#include<stdio.h>
#include<string.h>
int main()
{
char x[100],y[100];
scanf("%s%s",&x,&y);
for(int i=0;i<strlen(x);i++)
{
if(x[i]==y[i])
{
printf("0");
}
else
{
printf("1");
}
}
return 0;
}
Image: Error in testcase 99
That use of scanf is dangerous. It can lead to a buffer-overflow, that will produce undefined behaviour (behaviour may be different on different platforms, or even each time that you run the program).
Turn on compiler warnings. Use a good static analysis tool, or better use a safer language such as golang. Then use scanf format strings that prevent buffer overrun. On gcc the option -Wall will turn on this warning. You may also want to turn on some other warnings, or turn up the level to be more strict (especially for new code).
You have some issues in your code:
char x[100],y[100];
scanf("%s%s",&x,&y);
The type of second and third argument for scanf is not correct. They may have correct value, but strictly speaking they are wrong.
You need a char* but you provide a char (*)[]. You should just use x,y without the &.
Also you do not take care about potential buffer overflows.
To avoid buffer overflows, you should add a length limit to your format specifier. It must be one less than the size of your arrays.
Also you are required to deal with numbers up to 100 digits. That does not fit into your buffers.
If you need to handle strings of length 100, your arrays must have size 101.
You don't do this. If you get a string that is too long for one of your arrays, you will probably overflow into the next buffer losing the terminator byte.
That said, the 2 lines above should look like this:
char x[101],y[101];
scanf("%100s%100s", x, y);
Additionally you should always check return value of scanf and other IO functions.
To improve performance a bit, you should also not call strlen in each iteration of the loop. Instead you should call it once before the loop and store the value to use it in the loop condition.

Storing integer in char buffer array becomes binary value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array of integers, for example:
I memcpy the value into a char buffer, and the next time I retrieve it, it becomes a binary value, for example, 00000 -> 16. How do I avoid this?
Here is a snippet of my code:
char buf[BUFSIZE];
int outgoingPorts[4] = { 100000, 100001, 100002, 100003 };
memcpy(buf, &outgoingPorts[0], sizeof(outgoingPorts[0]);
printf("Port no: %i\n", buf);
Here, buf or the first outgoing port is 16 instead of 10000.
First of all, you're using wrong format specifier altogether, for the content of a char pointer to be printed, you need to use %s, provided that char array in null-terminated. Otherwise, you'll face undefined behaviour.
Then, if you really want to store an int value in a char array, the most suited way to go is to make use of snprintf() to print that value in the char array. Maybe the following pseudo-code will help you
char carr[16];
snprintf(carr, 16, "%d", outgoingPorts[0]);
printf("%s\n", carr); //should print 100000
FWIW, using wrong or mismatched format specifier invokes undefined behaviour.

In C, how can I check if the content of a string is not a number (where negative numbers are allowed)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Suppose my string is "g9". I want my check to indicate that the string doesn't contain a number. However
if my string is "123" or "-123", it should indicate that it's a number and it should return that string.
This can be done at least in two ways:
Using atoi function which parses string until first invalid character is encountered and returns integer number evaluated so far. Unfortunately, it provides almost no means for diagnostics.
Better option is strtol which basically does the same thing, but returns pointer to first invalid character and sets errno if any error is encountered. Typical usage:
#include <stdlib.h>
...
const char* const numStr = "123";
char* end;
const long i = strtol(numStr, &end, 10);
The end parameter allows you to check if the whole string was recognised as a valid number (in this case corresponding character is '\0'):
const int ok = (*end == '\0' && end != numStr);
Follow provided links for examples and more info. Also, you may consider related functions in See also section.

invalid conversion from `char' to `char*' [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
code is :
int main() {
int i,last;
char TXT[500];
printf("Donnez un exemple ?\n");
gets(TXT);
last = strlen(TXT);
for(i=0;i<50;i++){
if (i==0){
strcpy(TXT[1],TXT[0]);
} else {
strcpy(TXT[i-1],TXT[i]);
}
}
getch();
return 0;
}
error in line : strcpy(TXT[1],TXT[0]);
What is the cause of the problem ?
The strcpy function takes two char* (technically, a char* and a const char*). Moreover, it is not allowed to pass strcpy overlapping buffers.
It looks like you wanted to write
TXT[i-1] = TXT[i];
(this would delete the leading character from the string).
for(i=1 /* one, not zero */ ; i<50 ; i++) {
TXT[i-1] = TXT[i];
}
Good, but I want to use strcpy. How?
You are not allowed to use strcpy without an intermediate buffer. If you must use strcpy, do it like this:
char TXT[500], TMP[500];
printf("Donnez un exemple ?\n");
fgets(TXT, 499, stdin);
strcpy(TMP, &TXT[1]); // Note that 'for' loop is no longer required
TXT is an array of 500 characters.
So, TXT[1] and TXT[0] are individual characters (just one single letter).
TXT[0] is the very first character in the array.
TXT[1] is the second character in the array.
The function strcpy expects you to pass POINTER-to-characters (type char*) for both parameters.
And instead, you're passing a single character.
Can you explain what the purpose of this program is?
Maybe we can help you fix it then.
TXT[i] is of type char. But strcpy expects parameters of type char* since it operates on null-terminated strings. Hence the compilation error.
As for how to fix it, that depends on what your code is trying to do. Perhaps all you meant to do was
TXT[1] = TXT[0];
STRING FUNCTIONS WORKS ON STRING NOT ON CHARACTERS
ARE YOU TRYING TO SWAP THE WORDS OR CHARACTERS ?

Forcing users to write input in a specific format [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
i'm making a program in C. that keeps track of items in a warehouse.
and i want to force the user to include at least one number!
example dvd1, dvd2. hello1, hello20
is there a way to do this?
at this moment i am using scanf.
and i want the product code to have the requirement format of xx-xxx-xxx were x are numbers.
i'm using scanf ( %[0-9-]s
Mvh Anton!
scanf doesn't work like that, it doesn't have in-depth validation.
You need to read the input into a char array, then loop through each character and see if it is a digit.
Something like this (untested):
char buffer[1000];
int i = 0, hasDigit = 0;
scanf("%s", buffer);
while (i < sizeof(buffer) && buffer[i] != 0 && !hasDigit)
{
hasDigit = isdigit(buffer[i]);
i++;
}
// if hasDigit is 0, there are no digits
Note: scanf isn't great, since if you enter more characters than fit in the buffer it can cause a buffer overflow. It is better to use fgets(buffer, sizeof(buffer), stdin);
Read the input and you can iterate through as in This SO question. You can check to see if chars match the input you want pretty easily from that point on.

Resources