how to get first word in string and convert to int - c

I have a char array, and I want to get the first number from it.
e.g if my char array is 34 400 43 33. I want 34 as in int.
int FirstInt(char chars[])
{
return atoi(chars.substr(0, bursts.find(' ')));
}
I was thinkign something like this but it is not valid. ANy ideas?

int FirstInt(char chars[])
{
int x;
sscanf(chars, "%d", &x);
return x;
}

You don't need to tokenize the string or use sscanf if all you want is the first number:
return atoi(str);
From the man page
The atoi() function converts the initial portion of the string pointed
to by nptr to int
Which means it will stop when it finds a non-numeric character, like a white space.
Edit:
Note that it's impossible to detect errors with atoi, since it returns 0 on error in some implementations and doesn't set errno (AFAIK), so it's probably better to use strtol
See this link Converting Strings to Numbers

Related

atoi ignores a letter in the string to convert

I'm using atoi to convert a string integer value into integer.
But first I wanted to test different cases of the function so I have used the following code
#include <stdio.h>
int main(void)
{
char *a ="01e";
char *b = "0e1";
char *c= "e01";
int e=0,f=0,g=0;
e=atoi(a);
f=atoi(b);
g=atoi(c);
printf("e= %d f= %d g=%d ",e,f,g);
return 0;
}
this code returns e= 1 f= 0 g=0
I don't get why it returns 1 for "01e"
that's because atoi is an unsafe and obsolete function to parse integers.
It parses & stops when a non-digit is encountered, even if the text is globally not a number.
If the first encountered char is not a space or a digit (or a plus/minus sign), it just returns 0
Good luck figuring out if user input is valid with those (at least scanf-type functions are able to return 0 or 1 whether the string cannot be parsed at all as an integer, even if they have the same behaviour with strings starting with integers) ...
It's safer to use functions such as strtol which checks that the whole string is a number, and are even able to tell you from which character it is invalid when parsing with the proper options set.
Example of usage:
const char *string_as_number = "01e";
char *temp;
long value = strtol(string_as_number,&temp,10); // using base 10
if (temp != string_as_number && *temp == '\0')
{
// okay, string is not empty (or not only spaces) & properly parsed till the end as an integer number: we can trust "value"
}
else
{
printf("Cannot parse string: junk chars found at %s\n",temp);
}
You are missing an opportunity: Write your own atoi. Call it Input2Integer or something other than atoi.
int Input2Integer( Str )
Note, you have a pointer to a string and you will need to establish when to start, how to calculate the result and when to end.
First: Set return value to zero.
Second: Loop over string while it is not null '\0'.
Third: return when the input character is not a valid digit.
Fourth: modify the return value based on the valid input character.
Then come back and explain why atoi works the way it does. You will learn. We will smile.

Using atof() function in C with multiple input values

The goal of this program is to create a function which reads in a single string, user typed, command (ultimately for program to be used in conjunction with a robot) which consists of an unknown command word(stored and printed as command), and an unknown number of decimal parameters(the quantity is stored and printed as num, and the parameters are to be stored as float values in the array params). In the User input, the command and parameters will be separated by spaces. I believe my issue is with the atof function when I go to extract the decimal values from the string. What am I doing wrong? Thank you for the help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void func(char *input, char *command, int *num, float *params);
int main()
{
char input[40]={};
char command[40]={};
int num;
float params[10];
printf("Please enter your command: ");
gets(input);
func(input,command,&num,params);
printf("\n\nInput: %s",input);
printf("\nCommand: %s",command);
printf("\n# of parameters: %d",num);
printf("\nParameters: %f\n\n",params);
return 0;
}
void func(char *input, char *command, int *num, float *params)
{
int i=0, k=0, j=0, l=0;
int n=0;
while(input[i]!=32)
{
command[i]=input[i];
i++;
}
for (k=0; k<40;k++)
{
if ((input[k]==32)&&(input[k-1]!=32))
{
n++;
}
}
*num=n;
while (j<n)
{
for (l=0;l<40;l++)
{
if((input[l-1]==32)&&(input[l]!=32))
{
params[j]=atof(input[l]);
j++;
}
}
}
}
A Sample Output Screen:
Please enter your command: Move 10 -10
Input: Move 10 -10
Command: Move
# of parameters: 2
Parameters: 0.000000
The Parameters output should, ideally, read "10 -10" for the output. Thanks!
Change atof(input[l]) to atof(input + l). input[l] is single char but you want to get substring from l position. See also strtod() function.
Other people have already remarked the problem in your code, but may I suggest that you have a look at strtod() instead?
While both atof() and strtod() discard spaces at the start for you (so you don't need to do it manually), strtod() will point you to the end of the number, so that you know where to continue:
while(j < MAX_PARAMS) // avoid a buffer overflow via this check
{
params[j] = strtod(ptr, &end); // `end` is where your number ends
if(ptr == end) // if end == ptr, input wasn't a number (say, if there are none left)
break;
// input was a number, so ...
ptr = end; // continue at end for next iteration
j++; // increment number of params
}
Do note that the above solution does not differentiate between invalid arguments (say, foo instead of 3.5) and missing ones (because we've hit the last argument). You can check for that by doing this: if(!str[strspn(str, " \t\v\r\n\f")]) --- this checks if we're at the end of string (but allowing trailing whitespace). See the second side-note for what it does.
SIDE-NOTES:
You can use ' ' instead of 32 to check for space; this has two advantages:
It is clearer to the reader (it's very clear that it's a whitespace, instead of "some magic number that happens to have meaning")
It works in non-ASCII encodings (and the standard allows other encodings, though ASCII is by far the most popular; one common encoding is EBCDIC)
For future reference, this trick can help you skip whitespace: ptr += strspn(ptr, " \t\v\r\n\f");. strspn returns the number of characters at the start of the string that match the set (in this case, one of " \t\v\r\n"). Check documentation for more info.
Example for strspn: strspn("abbcbaa", "ab"); returns 3 because you have aab (which match) before c (which doesn't).
you are trying to convert a char into a float,
params[j]=atof(input[l]);
you should get the entire word(substring) of the float.
Example, "12.01" a null terminated string with 5 characters and pass it to atof, atof("12.01") and it will return a double of 12.01.
so, you should first extract the string for each float parameter and pass it to atof
Avoid comparing character to ascii value, rather you could have use ' ' (space) directly.
Instead of using for loop with a fixed size, you can use strlen() or strnlen() to find the length of the input string.

What is wrong with the program?

I'm extremely new to C and am doing a few problems I found in a book I bought. What is wrong with this program?
int main (void)
{
char text[50]='\0';
scanf ("%s", text);
printf("%c", text[49]);
printf("%s", text);
return 0;
}
char text[50]='\0';
is not valid. You could skip initialising text and just declare it
char text[50];
or you could initialise its first element
char text[50]={'\0'};
You're also missing an include of stdio.h and should really check that your scanf call read a string and could give it a max length for the string
if (scanf("%49s", text) == 1)
You want to get rid of:
printf("%c", text[49]);
as you have no idea what's at that memory location if the string is less than 49 chars long.
There is a difference of single quotes and double quotes in C.
double quotes means string
single quotes means character
Line 3 will not compile because the compiler wants you to assign a string to the array of characters.
You can do
char text[50]="\0";
which in effect fills all the 50 bytes with zeros.
You could also do
char text[50]="bla";
which fills the first 3 bytes with "bla" and the rest with zeros. At least my compiler does it like that.
You could also do nothing because you anyway fill it with user input just the next statement.
char text[50];
scanf ("%s", text);
But then you have a problem. Because the very next statement will give you random output if the user has entered a string with less than 49 characters. But if you initialize, well then you output the zero byte, which is also quite useless.
The main point however is to learn the different behaviour of C when dealing with an array of characters.
int main ()
{
char text[50]={'1','2','3','4'};
printf("%c", text[1]);
printf("%c",text[0]);
getch();
return 0;
}
do like this..

understanding ATOI function

Hi I have a text file which contains the below data
ABC00011234567
XYZ00021234567
To get the data, i have defined a structure
typedef struct data {
char x[3];
char y[4];
char z[7];
} key;
in the program what I do is read each line and assign it to the structure
unsigned char buf[1024];
fgets(buf,sizeof(buf),fptr);
key *k=(key*)buf;
int y = atoi(k->y)
printf( "y=%d\n",y);`
I'm getting the output as
y=1123456
y=2123456
the output Im expecting is
y=1
y=2
should I assume, atoi takes the pointer of the string and iterates till EOF is encountered?
what should I do to get the values 1 and 2?
atoi takes a nul-terminated string. You'll have to add your own terminators to your key members if you want to limit the length of data atoi parses
You should assume that atoi() keeps going until it reaches the end of the string or an invalid character. For example, for the string `"123zzz" it'd return 123.
You should either terminate your strings (put a zero at the end of them) and stop using atoi() (e.g. use strtol() instead); or write your own conversion that doesn't need a terminated string.
Note: (in general) atoi() should never be used for anything other than writing a compiler, because it does things that don't make sense to normal people (e.g. "0129" is 10 and not 129 because it decides the number is octal and the 9 isn't a valid digit for octal).
The atoi function expects a null-terminated string; you are passing a portion of the char array that has its termination past the boundaries of key::y, so atoi interprets the entire value as a number. If you would like to stick to your "cookie cutter" method of parsing the key, you need to make a copy, and pass it to atoi:
char temp[5];
memcpy(temp, k->y, 4);
temp[4] = '\0';
int y = atoi(temp);
However, I think that using fscanf is a better choice:
char x[4];
int y, z;
fscanf(fptr, "%3s%4d%7d", x, &y, &z);
printf("%s %d %d", x, y, z);
atoi() assumes a zero terminated string. In your case, the string will not be zero-terminated, and thus the data in z is read by atoi after y has been read.
To read just the 4 digits, you can use sscanf:
sscanf(k->y,"%4d",&y);

Why do I get this unexpected result using atoi() in C?

I don't understand the results of the following C code.
main()
{
char s[] = "AAA";
advanceString(s);
}
void advanceString(p[3])
{
int val = atoi(p);
printf("The atoi val is %d\n",val);
}
Here the atoi value is shown as 0, but I could not figure out the exact reason.
As per my understanding, it should be the summation of decimal equivalent of each values in the array? Please correct me if I am wrong.
atoi() converts a string representation of an integer into its value. It will not convert arbitrary characters into their decimal value. For instance:
int main(void)
{
const char *string="12345";
printf("The value of %s is %d\n", string, atoi(string));
return 0;
}
There's nothing in the standard C library that will convert "A" to 65 or "Z" to 90, you'd need to write that yourself, specifically for whatever charset you're expecting as input.
Now that you know what atoi() does, please don't use it to deal with numeric input in whatever you come up with. You really should deal with input not being what you expect. Hmm, what happens when I enter 65 instead of A? Teachers love to break things.
atoi() doesn't do any error checking whatsoever, which makes anything relying on it to convert arbitrary input fragile, at best. Instead, use strtol() (POSIX centric example):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
static const char *input ="123abc";
char *garbage = NULL;
long value = 0;
errno = 0;
value = strtol(input, &garbage, 0);
switch (errno) {
case ERANGE:
printf("The data could not be represented.\n");
return 1;
// host-specific (GNU/Linux in my case)
case EINVAL:
printf("Unsupported base / radix.\n");
return 1;
}
printf("The value is %ld, leftover garbage in the string is %s\n",
// Again, host-specific, avoid trying to print NULL.
value, garbage == NULL ? "N/A" : garbage);
return 0;
}
When run, this gives:
The value is 123, leftover garbage in
the string is abc
If you don't care about saving / examining the garbage, you can set the second argument to NULL. There is no need to free(garbage). Also note, if you pass 0 as the third argument, it's assumed the input is the desired value of a decimal, hex or octal representation. If you need a radix of 10, use 10 - it will fail if the input is not as you expect.
You'd also check the return value for the maximum and minimum value a long int can handle. However, if either are returned to indicate an error, errno is set. An exercise for the reader is to change *input from 123abc to abc123.
It's important to check the return, as your example shows what happens if you don't. AbcDeFg is not a string representation of an integer, and you need to deal with that in your function.
For your implementation, the most basic advice I can give you would be a series of switches, something like:
// signed, since a return value of 0 is acceptable (NULL), -1
// means failure
int ascii_to_ascii_val(const char *in)
{
switch(in) {
// 64 other cases before 'A'
case 'A':
return 65;
// keep going from here
default:
return -1; // failure
}
.. then just run that in a loop.
Or, pre-populate a dictionary that a lookup function could scope (better). You wouldn't need hashes, just a key -> value store since you know what it's going to contain in advance, where the standard ASCII characters are keys, and their corresponding identifiers are values.
It tries to convert the string into an integer. Since AAA cannot be converted into an integer the value is 0. Try giving it 42 or something.
If no valid conversion could be
performed, a zero value is returned.
See http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
Read atoi() as a to i (ASCII to integer).
atoi() converts a string representing a decimal number, to integer.
char s[] = "42";
int num = atoi(s); //The value of num is 42.
atoi expects its argument to be a string representation of a decimal (base-10) integer constant; AAA is not a valid decimal integer constant, so atoi returns 0 because it has no other way to indicate that the input is invalid.
Note that atoi will convert up to the first character that isn't part of a valid integer constant; in other words, "123" and "123w" will both be converted to 123.
Like everyone else is saying, don't use atoi; use strtol instead.

Resources