EDIT : Ok,so answer was told by #Mischo5500. Thank you all,guys
How to find out how much numbers are in array except space? My program will find out length of array, until user input will be space and that is the problem. So if I have inserted "10 20 300", the length will be 2. I have expected 3,like three numbers,which were inserted.And I don't know,how much numbers will user type in. I have already tried strlen(p),it was the same thing. Can you help me? Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
float p[1000];
scanf("%f",p);
int length=(sizeof(p)/sizeof(float));
printf("%d",length);
return 0;
}
If i tike it right (sorry if not), you want to calculate number of entered float values. It is easier for you to insert them in string format and convert them to float after processing, if you don't know number of arguments, that will be typed in. Here is how your code can look like for example, float numbers are in val variable, number of inserted values is in length variable.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char p[1000];
float val[1000];
int length = 0;
char* itr;
fgets(p, sizeof(p), stdin);
itr = strtok(p, " ");
while(itr != NULL)
{
val[length] = atof(itr);
itr = strtok(NULL, " ");
length++;
}
printf("%d",length);
return 0;
}
EDIT: If you want "length" of first element, just use strlen() on first token
itr = strtok(p, " \n");
if(itr)
{
length = strlen(itr);
val[length] = atof(itr);
}
You can take in the user inputs in the form of command-line arguments which get passed in to the program as
int main(int argc, char *argv[])
That will give you the entire length of arguments. You would convert each of the arguments argv[i] to numbers.
Related
Hello I am new to C and I am trying to create a list of strings. But when I try to define the list uninitialized it gives me an error. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int size;
char *sentence = "";
char *allWords[]; //incomplete type is not allowed
scanf("%d *[^\n]", &size);
fgets(sentence, size + 1, stdin);
return 0;
}
Instead of doing that you can just define a variable, BUFFER in this case for the lenght of the strings and ask for the size of the array list, then you can just make a for loop to store each value in a postion of the array list if you want with strcpy function (You cant use == to compare strings in C, that only work with chars because you're comparing ASCII value, for example 'a' == 97 is true).
#include <stdio.h>
#include <stdlib.h>
#define BUFFER 50
int main(){
int size;
char sentence[BUFFER];
printf("Introduce the size of the array list:");
scanf("%d", &size);
char allWords[size][BUFFER];
fgets(sentence, size + 1, stdin);
// Then you can insert the "sentence" in the array list with strcpy function included in <string.h>
strcpy(allWords[Position], sentence); //Position not declared in this case, is just an example, you can use this in a loop with a variable iterating each position of the array list
return 0;
}
I am working on creating a shell and I haven't use C for a while. I have the shell initizing properly but when I try to compare the user input to an array of strings I have I get a segmentation fault. I was planning on adding casce statements in a the for loop to initiate each of the processes once they are called by the user. I haven't included those since I have been trying to figure out how to get the user input to match with a value in my string array. Under debug I was only receiving the first character of the builtins[j] value which kind of makes since since it is a pointer right. However I am stuck and could use some ideas for why this isn't returning 0 when I input "exit". Thanks
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
//This code is for creating a basic shell
void init_shell(int num, char *prompt[]){
char s1[] = "-p";
int result;
if(num>1){
result = strcmp(s1, prompt[1]);
if(result==0){
printf("%s>$", prompt[2]);
}else{
printf("308sh>$");
}
}
//printf("%s\n %s\n %s\n %d\n", prompt[0], prompt[1], prompt[2], result);
else{
printf("308sh>$");
}
}
//The infinite loop for accepting user input until it closes
int main(int argc, char *argv[]){
const char *builtins[7];
builtins[0] = "exit\n";
builtins[1] = "pid\n";
builtins[2] = "ppid\n";
builtins[3] = "cd\n";
builtins[4] = "pwd\n";
builtins[5] = "set\n";
builtins[6] = "get\n";
char usr_in[]="";
char cmp[]="";
while(1==1){
init_shell(argc, argv);//intial prompt for the shell
fgets(usr_in,100,stdin);
//Check for builtin Commands
int cmds_size = 7;
int j=0;
int res;
for(j; j<cmds_size; j++){
res=strcmp(usr_in, hold);
if(res==0){
printf("Execucting\n");
}
else{
printf("no command\n");
}
}
}
return(0);
}
The issue here is that you're writing the user's input to a buffer that isn't big enough to hold anything other than a null terminator.
char user_in[] = "";
The above line tells the C compiler that you need just enough space to store [ '\0' ], which is a single byte. The C compiler doesn't know that you may later write a 100-byte string to that buffer.
When you write to the buffer, the user's input overflows and will overwrite other values in your stack. Since the other values in your stack are pointers, what'll happen is you'll run into seg-faults, since you're writing character values into those bytes, but interpreting them as char pointers.
You are correctly limiting the size of the allowed input from the user to 100 characters, but you should make sure that your buffer is big enough to hold the value you're reading in:
char user_in[101];
for(int i = 0; i < sizeof(user_in) / sizeof(user_in[0]); i++) {
user_in[i] = 0; // Since this is allocated on the stack *in main*, this
// shouldn't be necessary
}
Here's one example of how you can rewrite your main method:
#include <stdio.h>
#include <string.h>
typedef enum { false, true } bool; // If you don't have this
// defined already
int main(int argc, char *argv[]) {
const char *builtins[7];
builtins[0] = "exit\n";
builtins[1] = "pid\n";
builtins[2] = "ppid\n";
builtins[3] = "cd\n";
builtins[4] = "pwd\n";
builtins[5] = "set\n";
builtins[6] = "get\n";
char user_in[101];
for(int i = 0; i < sizeof(user_in) / sizeof(user_in[0]); i++) {
user_in[i] = 0;
}
while(1) {
printf("Enter a command: ");
fgets(user_in, 100, stdin);
bool found = false;
for(int i = 0; i < sizeof(builtins) / sizeof(builtins[0]); i++) {
if (!strcmp(user_in, builtins[i])) {
printf("Found command %s", builtins[i]);
found = true;
break;
}
}
if (!found) {
printf("Didn't find command\n");
}
}
return 0;
}
Also, regarding your function init_shell: you're checking to see if argc is greater than 1, but that only guarantees that argv[1] is defined; it doesn't guarantee that argv[2] is defined. (Remember, argc is the size of the argv array, where the first element is the name of the program being executed). You want to make sure that argc is at least 3 before checking for the prompt flag in the way you are.
It may be overkill for your use-case, but consider using the getopt function for getting a custom prompt value from the user. See http://man7.org/linux/man-pages/man3/getopt.3.html for documentation regarding that method.
This is my String "This is just a text. Data: Is invalid. Restful information. Actual Position:1234 System requirements".
My searched string is "Actual Position:" and I am interested in having the number infront which changes all the time the motor is moved. Thanks for your help.
You should be able to use sscanf (see scanf for format) for this. You can do something along the lines of this.
#include <stdio.h>
#include <string.h>
int main ()
{
int i=-1;
char sentence[]="This is just a text. Data: Is invalid. Restful information. Actual Position:1234 System requirements";
char key[]="Actual Position:";
char* subst= strstr(sentence, key);
if(subst != 0){
int n = sscanf (subst,"Actual Position:%i",&i);
if (n > 0){
printf ("Found Actual Position => %d\n",i);
}
}
return 0;
}
You have to use strstr to search, then use the position pointer with the length of "Actual Position:" and finally use the sscanf to read the value:
#include <stdio.h>
#include <string.h>
int main()
{
char data[] = "This is just a text. Data: Is invalid. Restful information. Actual Position:1234 System requirements";
char srcData[] = "Actual Position:";
char *pos = strstr(data, srcData) + strlen(srcData);
int value = 0;
sscanf(pos, "%d",&value);
printf("%d",value);
return 0;
}
First, my objective with this code: take in a sentence into a C string. Iterate through the sentence and see how many instances of a particular letter occur.
This code is working somewhat but not giving the right number? Not sure why:
#include <stdio.h>
#include <string.h>
int tracker=0;
int letterCount (char *sentence)
{
int s=strlen(sentence);
int i=0;
for (i=0; i<s; i++){
if (sentence[i]=='h') {
tracker++;
}
}
return tracker;
}
int main(int argc, const char * argv[])
{
char *string="Hi there, what's going on? How's it going?";
letterCount(string);
printf("this sentensce has %i H's", tracker);
return 0;
}
The output I'm getting:
this sentensce has 2 H's
Not quite right. Any ideas?
This is the correct code if you mean case insensitive H:
#include <stdio.h>
#include <string.h>
int tracker=0;
int letterCount (char *sentence)
{
int s=strlen(sentence);
int i=0;
for (i=0; i<s; i++){
if (sentence[i]=='h' || sentence[i]=='H') { //'h' is not the same as 'H'
tracker++;
}
}
return tracker;
}
int main(int argc, const char * argv[])
{
char *string="Hi there, what's going on? How's it going?";
letterCount(string);
printf("this sentensce has %i H's", tracker);
return 0;
}
You have just mispelled small and the capital letter in your code.
Remember, the C language is case sensitive!
Although your label talks about the number of Hs, your letterCount looks for hs instead -- and it looks to me like the input you've provided does have two instances of lower-case h, just as it says.
If you want to count them together, you might consider filtering each input with tolower or toupper before checking what you have.
That number looks correct to me: you have 2 'h' characters in that sentence. If you want to count the 'H' characters as well, then you need a separate check.
size_t letterCount(const char* sentence, char c)
{
size_t count = 0;
while(sentence)
{
count += (*sentence == c);
++sentence;
}
return count;
}
What do we see here?
You can't have negative count, so use an unsigned type like size_t
sentence shouldn't be modified, so it should be const
pass in the char you want to match
sentence is a pointer, if it is null you are done. Don't need to call strlen.
sentence is a pointer, the actual pointer is pass by value, so you can modify it (see the increment, no need to make an extra variable)
boolean operators return 1 or 0, so no need to use the if. (Although, I haven't looked at the assembly to see if an if branch or an add 0 is cheaper. YMMV)
I tried to write a function, that get a number of candidates betwen 10 to 60,000,
and gets a name for each candidate...
This is what I wrote:
/********** Headers **********/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
/********** Consts **********/
const number_candidates;
/********** Functions **********/
void get_candidates(char *arr[256][256])
{
int counter = 1, i = 0, j =0;
int temp = 0;
printf ("Please enter the number of candidates: \n");
scanf ("%d", &temp);
while (temp < 10 && temp > 60000)
{
printf ("Please enter the number of candidates: \n");
scanf ("%d", temp);
}
const number_candidates = temp;
while (counter < number_candidates + 1)
{
printf ("Please enter the %d name: \n", counter);
fgets (arr, 256, stdin);
counter++;
}
}
int main(int argc, char *argv[])
{
int i = 0;
char can_names[256][256];
get_candidates(&can_names);
system("PAUSE");
return 0;
}
There is an error in getting the names into the arr...
You should avoid using arguments like this one: char *arr[256][256] ... what's the point of it? You should think about what your function will do. You want it to load names of candidates right? So you could define struct candidate with an attribute name within it:
typedef struct candidate{
char name[256];
} Candidate;
Another thing: why are you passing an address of your array to this function? You just want your array to be filled with data, you won't work with an array itself, thus it's enough to pass an array, not an address of it.
Then prototype of your function could be changed to void get_candidates(Candidate* candidates) which is much easier to read. And look how simple can usage of this function become:
Candidate candidates[256];
get_candidates(candidates);
And last thing: before you write function like that, try something simpler first (to find out what's happening there).
Here's an example:
#include <stdio.h>
typedef struct candidate{
char name[256];
} Candidate;
void get_candidates(Candidate* candidates){
scanf("%255s", candidates[4].name);
}
int main(int argc, char *argv[]){
Candidate candidates[256];
get_candidates(candidates);
printf("%s\n", candidates[4].name);
return 0;
}
In case you don't know the count of candidates before calling get_candidates, then it's better to change the prototype of this function to Candidate* get_candidates() so that it's clear that this function creates an array:
// caller is responsible for calling free on return value
Candidate* get_candidates(){
Candidate* candidates;
int count = 50; // here you found out the count
candidates = malloc(count*sizeof(Candidate));
fgets(candidates[4].name, 255, stdin);
return candidates;
}
int main(int argc, char *argv[]){
Candidate* candidates = get_candidates();
printf("%s\n", candidates[4].name);
free(candidates);
return 0;
}
You should call:
counter = 0;...fgets (arr[counter], 256, stdin);
You need walk one step for each loop.
Have a look at the documentation for scanf which indicates that variables need to be passed as a pointer as you did the first time you call scanf. Then have a look at your second call to scanf...
You're currently only assigning names to the first string in your array over and over again. Look at that while loop and in particular, how you're passing in the 'arr' variable. Have a look here for some inspiration.
To print out all of the names you need to loop over the array. You can find some examples of printing a list of strings here and here.
A few things are wrong:
First, you need space for 60000 names, yet you only allocate enough for 256. OK, we change
char can_names[256][256];
to
char can_names[60000][256];
and get... a segmentation fault, probably. That's because the array is using too much stack space. Change it to
static char can_names[60000][256];
so it's not on the stack.
Second, there's no need to take the address of the array - it's already passed as a pointer. Your function call changes to
get_candidates(can_names);
and the function signature is
void get_candidates(char arr[60000][256])
Third, you need a loop to read the entries one at a time. A for loop is easier to read:
for (counter = 0; counter < number_candidates; counter++)
{
printf ("Please enter the %d name: \n", counter);
fgets (arr[counter], 256, stdin);
}
Fourth, the condition
while (temp < 10 && temp > 60000)
should be
while (temp < 10 || temp > 60000)
(how can a number be both less than 10 and greater than 60000?) Once this is fixed, you can remove the initial read of temp since the loop will run at least once. Note that if you type a letter instead of a number now, the program will go into an infinite loop (it will repeatedly read the letter). Fixing this is left as an exercise.
Fifth, you don't need any headers except stdio.h. Also, the i and j variables are unused.
Edit: missed the scanf error. scanf takes addresses as parameters. it makes sense too: scanf needs somewhere to store a value, it doesn't care about the current value. So the call to scanf should be:
scanf ("%d", &temp);
Don't know if this would help but have a look at the code below.
It works dynamically ie. it allocated memory for desired no of candidates rather than assuming 60,000 of them.
/*
* Write a function, that get a number of candidates betwen 10 to 60,000, and gets a name for each candidate
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 256
int main(int argc, char*argv[]){
int i,n;
char **s;
printf("Enter the total number of candidates\n");
scanf("%d",&n);
//error condition
if(n<10 || n>60000){
printf("Sorry number of candidates should be between 10 to 60,000\n");
return -1;
}
//allocate memory
s = malloc(sizeof(char*)*n);
//get the data
for(i=0;i<n;i++){
s[i] = calloc(MAX,sizeof(char));
printf("Enter the candidate number %d's name:\n",i+1);
//fgets(s[i],MAX,stdin);
scanf("%s",s[i]);
}
//Display the data
printf("\nDetails of all the Candidates\n\n");
for(i=0;i<n;i++){
printf("Candidate number %d's name:%s\n",i+1,s[i]);
}
//Free the memory
for(i=0;i<n;i++){
free(s[i]);
}
free(s);
return 0;
}
I had a problem with fgets it was skipping the first candidate info. Any help would be appreciated.. I tried flush(stdin) but did not solve the issue.