'Character Array' of integers to 'Integer 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
My Requirement :
Taking some (unknown number) of integers as input from user and store them in a numeric array.
Eg: input: 25 3 4 78. I want them to be stored in a numeric array, say num as
num[0] = 25
num[1] = 3
num[2] = 4
num[3] = 78
. . .
What I did :
Stored the input in a character array.
gets(arr);
//takes input from command prompt and stores in a string
Then I'm trying to find spaces and separate the characters, but it turns out that a double digit number(say,25) is stored as 2 and 5 but not as 25.
How do I achieve this?

Well, as you did not show your code, I'll also not provide any code, but I'll be more than happy to provide you with the flow-chart.
Define one array large enough (maybe change to dynamic allocation later).
Take the input from user (not command line arguments) using fgets().
use strtok() to tokenize the input using space as delimiter.
If a non-NULL token is received, use strtol() to convert the token to int or long.
If strtok() returned NULL means you've got all the tokens and the input is empty, finish up, you got your int array.

Related

Print a string without knowing max size [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am supposed to print out Number of letters in a word given by the user and also print it out in reverse. I struggle to find out how i am supposed to declare the array when i dont have the size of the string. I thought of using gets and then a for loop but can’t figure out how to define char in both the function for printing number of letters and printed in reverse.
When you obtain the string - say, with scanf() or fgets() - you can specify a maximum "field width", i.e. the maximum number of characters to read into your buffer. So, you first set the buffer size, then you read into it.
Now, after you've read the string, you can determine it's length the usual C way with strlen() on your buffer. Alternatively, if you're using scanf(), you can use the "%n" specifier to store the number of characters consumed, so that scanf("%49s%n", buffer, &count); will scan the string into the 50-chararacter-long buffer and the number of characters into count.
PS - Don't use the gets() function though... Why is the gets function so dangerous that it should not be used?
Counting characters in a word entered by the user is easy. Set a counter to zero. Read one character at a time (e.g., using getchar). If the character is a letter, increment the counter and continue the loop. If it is not a letter or the attempt to read fails (e.g., getchar returns EOF), exit the loop and print the value of the counter. For embellishment, you might add code to ignore white space before the letters start, to ignore white space after the letters end (until a new-line character is seen), and/or to report a warning if any other characters are seen. –
Eric Postpischil

My Strlen Syntax Not Written Well? [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 5 years ago.
Improve this question
if I write more than 20 charcters in my program it runs through it and skips my if statement if(length > 20). What did I do wrong?
printf("\nEnter Your Product:");
fgets(item_name, 20, stdin);
length = strlen(item_name);
if(length > 20){
Errorlevel("Input Greater Than 20");
}
You set fgets to gather a maximum of 20 chars. Thus, if(length > 20) is always false.
See documentation about fgets
The fgets will read up the the requested number of character minus one. The size you pass to the fgets function includes the terminator.
So no matter how many characters you write, the length will never be longer than 19 characters.
A simple way to check if to many characters were input is to see if the last character (not the string terminator) is a newline or not. If it's not then 19 or more characters were entered as input.

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.

Error Copying 1 string to another in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was trying to copy the contents of 1 string to another (a into b) .
I deliberately took the second string(b) to be smaller than the 1st
one(a) .
I copied the contents of the first one into second
. I added WATCH on both of them . In the Debug tab , I found out that while
copying the original string gets destroyed and the new one also
DISPLAYED LARGER than its size.
#include<stdio.h>
int main()
{
char a[10]="What?";
char b[2];
int i;
for(i=0;i<6;i++)
{
b[i]=a[i];
}
printf("This is %s",a);
printf("\n this is b now: ",b);
return 0;
}
I have attached the screenshot for the same. I took a = a string of
size 10 . a="WHat?" then I took a string b[2]
After copying , I printed both a and b . I expected the output to be
, a = "WHat?" , b="WH" But the output is coming something else.(See
the screenshot)
Why did the original string get destroyed ? Has the pointer changed ? But I have made it a constant pointer .It can't be changed.
Here is the Screen shot to the problem I am facing :
https://www.dropbox.com/s/8xwxwb27qis8xww/sjpt.jpg
Please Help Somebody !!
You are copying 6 bytes into an array of two bytes, essentially invoking undefined behavior.
You are passing array b to printf with %s specifier that expects a null-terminated string, while b is most likely not null-terminated at that point, which is another undefined behavior.
Also, a null-terminated string that can fit into 2 bytes array can essentially have only one printable character, so you should not expect b to be "WH". At best, if you fix the copying, it can only be "W" as the second character will be a termination byte (\0). If you want to have two characters, either increase the array size to 3 to allow for null terminator, or simply do not use C strings and print out two bytes using "%c%c" format string.
As pointed out in other answers, you are writing outside the bounds of the array. The original string a changes because it happens to be exactly after b in memory as you can see in the debug window.
Before the loop, memory looks like this:
b a
|00|WHat?00000|
After the loop, memory looks like this:
b a
|WH|at?0?00000|
This explains why
a is changed
the original questionmark in a is still there (you only write 6 characters - two into the location reserved for b, 4 (including null terminator) into the location of a)
Of course this is undefined behavior as already mentioned by Vlad Lazarenko, but it explains the behavior for your compiler/settings/version/etc.
A constant pointer only exists for the compiler. It ensures that you cannot explicitly manipulate its data, but if you have memory leaks, nothing can be guaranteed.
What you're doing currently is very unsafe! It might work on Windows for some godforsaken reason, but don't do this!
The C standard library has special functions for working with strings and memory, strcpy for example is for copying character arrays. I suggest you learn more about how strings work and how you can manipulate them.

atoi() returning 0 from char array [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 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?

Resources