So, I am trying to write an strncpy function. I want user to input the number of characters to be copied from source. I am doing something wrong, but I can't understand what. This is what I tried to do:
#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20
int main() {
char string[ARR_SIZE];
int n, m;
char s1[4], s2[4], nstr[m];
printf("Enter the string:");
gets(string);
printf("The length of the string is: %ld\n", strlen(string));
strcpy(s1, s2);
printf("The original string is: %s\n", string);
printf("The copy of the original string is: %s\n", string);
printf("How many characters do you want to take from this string to create another string? Enter: \n");
scanf("%d", &n);
strncpy(nstr, s1, m);
printf("%s\n", nstr);
}
(On top I tried some strlen and strcpy functions.)
EDIT: I totally forgot to write what was the problem. Problem is I can't get the new string which is named nstr in my code. Even though I printed it out.
first of all, the whole code is just a bad practice.
Anyway, here is my take on your code which copies n characters of an input string to string_copy
#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20
int main() {
char string[ARR_SIZE];
int n;
printf("Enter the string:");
gets(string);
printf("The length of the string is: %ld\n", strlen(string));
printf("The original string is: %s\n", string);
printf("How many characters do you want to take from this string to
create another string? Enter: \n");
scanf("%d", &n);
if(n > strlen(string)){
n = strlen(string);
printf("you are allowed to copy maximum of string length %d\n", n);
}
char string_copy[n];
strncpy(string_copy, string, n);
printf("%s\n", string_copy);
}
note that using deprecated functions such as gets() isn't safe. use scanf() or fgets() instead.
refer to why you shouldn't use gets()
Related
I am trying to implement DMA for char variable. But I am unable to take input. I tried with all the possible cases I know:
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
But I can't even enter input data for the character variable ptr_name. I want to take input as "string with space" as input value. How to solve this problem?
And then how to print the entered name in the screen?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
ptr_name = (char*)malloc(name);
printf("Enter name: ");
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
scanf("%d", ...) does not consume the enter so the next scanf() gets an empty string.
you can use getchar() to consume the enter.
Also, you need to allocate additional byte for the zero at the end of the string / string terminator. See the + 1 in malloc().
As for your questions, your commented scanf() had & before argument 2 which isn't expected (char ** vs. char *) but other than that it will allow spaces in strings. puts() will print the entered name, alternatively you can modify the above printf() to print the name, e.g: printf("\n Your name is: %s", ptr_name);
Lastly, please consult Specifying the maximum string length to scanf dynamically in C (like "%*s" in printf) for dynamically limiting the input size, avoiding buffer overflow.
DISCLAIMER: The following is only "make it work" version of the program above and is not intended for real life use without appropriately checking return codes and limiting the input size:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
getchar();
ptr_name = (char*)malloc(name + 1);
printf("Enter name: ");
scanf("%[^\n]", ptr_name);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
if you want to get input with spaces you need to use getline():
getline(&buffer,&size,stdin);
here an example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int len;
printf("Enter number of characters for Name: ");
scanf("%d",&len);
ptr_name = (char*)malloc(len);
printf("Enter name: ");
getline(&ptr_name, &len, stdin);
printf("\n Your name is: %s", ptr_name);
free(ptr_name);
return 0;
}
This question already has answers here:
fgets instructions gets skipped.Why?
(3 answers)
Closed 6 years ago.
#include<stdio.h>
#include<malloc.h>
int main()
{
char *string1;
int length;
scanf("%d", &length);
string1 = (char *)malloc(sizeof(char) * length);
printf("\n Enter the First String : ");
fgets(string1, length, stdin);
printf("\n The First String : %s ",string1);
free(string1);
return 0;
}
Can someone help me on the above code ? I trying to get the length of a string and the string as inputs. But, I am able to enter only Length of the string. After that it skips the string input part.
This is the output I am getting :
sh-4.3$ main
10
Enter the First String :
The First String :
sh-4.3$
After typing "10<enter>" the <enter> or "\n" will remain in the
stdin buffer, so you have to use getchar() after the scanf to
remove it.
Also you should #include <stdlib.h> instead of malloc.h.
You malloc 1 character too less, because of the 0-terminator.
string1 = malloc(length + 1); will do the job, the cast is not
necessary and sizeof(char) is always 1.
If you need to use stdin for string input you can use fgetln. I edited you example and now it looks like that:
#include<stdio.h>
#include <stdlib.h>
int main()
{
char *string1;
size_t length;
//scanf("%d", &length);
//string1 = (char *)malloc(sizeof(char) * length);
printf("\n Enter the First String : ");
//fgets(string1, length, stdin);
string1 = fgetln(stdin, &length);
string1[length] = '\0';
printf("\n The First String : %s ",string1);
free(string1);
return 0;
}
Note: fgetln returns not a C string, you should add a NULL character to the end.
The most simple answer when reading from STDIN/keyboard with the newline etc.
is to just add the "\n" to the scanf, ie:
scanf("%d\n", &length);
Solves the problem ;)
PS: Beware of all the other security/buffer overflow issues of scanf
Does it not return an int or something?
This is a snippet of my code:
int wordlength(char *x);
int main()
{
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
printf("Word Length: %d", wordlength(word));
return 0;
}
int wordlength(char *x)
{
int length = strlen(x);
return length;
}
Function strlen is applied to strings (character arrays) that have the terminating zero. You are applying the function to a pointer to a single character. So the program has undefined behaviour.
Change this part:
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
to:
char word[256]; // you need a string here, not just a single character
printf("Enter a word: \n");
scanf("%255s", word); // to read a string with scanf you need %s, not %c.
// Note also that you don't need an & for a string,
// and note that %255s prevents buffer overflow if
// the input string is too long.
You should also know that the compiler would have helped you with most of these problems if you had enabled warnings (e.g. gcc -Wall ...)
Update: For a sentence (i.e. a string including white space) you would need to use fgets:
char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);
This question already exists:
Safe Alternative to gets [duplicate]
Closed 8 years ago.
I know that I can use gets(char *) to get string input from user with spaces included but I read that buffer overflow problem. Using strcpy, strcmp (and a few other functions) is not safe we should use strncpy, strncmp and explicitly mention the size of the input. Some guy on Stack Overflow told me that. So, I am worried about using gets for getting input from user or it's safe? If it's safe tell me I'll continue using it. If not then what is the other way getting spaced string input from user safely?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *a[2];
char b[] = "first";
char c[] = "second";
int s1; //,s2;
// printf("\nLong you want your %s string to be: \n",b);
//scanf("%d",&s1); fflush(stdin);
//printf("\nLong you want your %s string to be: \n",c);
// scanf("%d",&s1); fflush(stdin);
int i;
for(i=0; i<2; i++) {
printf("\nLong you want your %s string to be: \n",b);
scanf("%d",&s1); fflush(stdin);
a[i] = (char *) malloc(s1*sizeof(char));
}
printf("\nEnter the first string: \n");
scanf("%s", a[0]); fflush(stdin);
printf("\nEnter the second string: \n");
scanf("%s", a[1]); fflush(stdin);
printf("\nThe first string is: %s\n", a[0]);
printf("\nThe second string is: %s\n", a[1]);
}
Please do some research.. this http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044652485&id=1043284385 may help you.
I need to write a function which takes 2 words and count its length. I wrote below one but this code only woks for 1st word. How can I improve it to count whole sentence?
#include <stdio.h>
int findlen(int *s);
int main(void)
{
char string1[80];
printf("Enter a string: ");
scanf("%s", string1);
printf("Lenght of %s is %d\n", string1, findlen(string1));
}
//find the length of the inputted string
int findlen(char *s)
{
int count = 0;
while (*s != '\0')
{
s++;
count++;
}
return count;
}
scanf will take the one word input only.. (i.e) it breaks when space appears..
Try fgets to read the complete string till \n
You can use fgets to safely get the line from your file:
From here:
char *fgets(char *s, int size, FILE *stream);
so replace your scanf line with:
fgets(string1, sizeof(string1), stdin);
If you used gets instead, it doesn't know how large your buffer is and it would crash when reading too large line.
Next, if you want to know a length of your string you could use strlen function from string.h:
#include<string.h>
...
printf("Lenght of %s is %d\n", string1, strlen(string1));
use [%^\n] format specifier so that it will scan the string till '\n' encounter so the problem in scanning string having space(eg. "hello word") will be solved.
scanf("[%^\n]",straddr);