#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
char *readline()
{
char s[256],*ds;
printf("Give string: ");
gets(s);
ds = (char *) calloc(strlen(s)+1,sizeof(char));
strcpy(ds,s);
return ds;
}
main()
{
char *s1,*s2;
int a,b;
s1=readline();
printf("Start:");
scanf("%d",&a);
printf("End:");
s2=(char*)realloc(s1,b-a);
puts(s2);
return 0;
}
I have this code and I want to resize specific cells of the s1 array which are determined from the variables a and b.
E.g. If I give the string "Hello" and the integers a=2 and b=4 then I want the program to print "ell".
Don't use gets use fgets instead.
With fgets you would use if( fgets( s,256, stdin)!= NULL ){ /*Got input in s*/ }.
You have taken \n as input also. s[strcspn(s,"\n")]=0 will overwrite \n with \0.
Casting return value of calloc is not needed since, void* will be implicitly converted to char*. calloc may return NULL - you didn't include check in there.
ds = calloc(strlen(s)+1,sizeof(char));
if( NULL == ds ){
perror("calloc: error");
exit(EXIT_FAILURE);
}
In main() value of b is indeterminate. You didn't take input in b.
if( scanf("%d",&b)!= 1){
fprintf(stderr,"Error in input");
exit(EXIT_FAILURE);
}
Then you realloc-ed. But not clear why. If you thought that shrinking the memory to 4-2 or 2 Bytes will help you get "ell" then you are wrong in many ways. It won't.
what you can do is - allocate memory for that in s2.
if(b<a){
fprintf(stderr,"End must be greater than beginnning\n");
exit(EXIT_FAILURE);
}
s2 = malloc(b-a+1);
if(!s2){
perror("calloc: error");
exit(EXIT_FAILURE);
}
memcpy(s2,s1+a,b-a);
s2[b-a]=0;
puts(s2);
This will print the relevant "ell" just you wanted. There is one thing left for you - put the code snippets in the code.
Since you are open to other solutions:
If there is another way then no problem.
I would point you to a simple solution, where you terminate the original string at b and skip required number of characters a. (Note: in C char array starts from index 0);
This is the idea:
#include <stdio.h>
#include <string.h>
char *splice(char *str, int s, int e)
{
str[e]=0;
return (str+s-1);
}
int main()
{
char *after;
int a=2;
int b=4;
char original[] = { 'H', 'e', 'l' , 'l' , 'o', 0 };
after = splice(original,a,b);
printf("My new string = %s", after);
return 0;
}
Output:
My new string = ell
Related
I want to make a program that has a key to open. But when i comparing the key and the input, it always says "Wrong":
#include <stdio.h>
int main(){
char key[5]="april",ckey[5];
printf("Enter the key: ");
scanf("%s",ckey);
if(ckey==key){
printf("Correct.");
}
else{
printf("Wrong.");
}
return 0;
}
Is it possible to solve the problem without using other libraries?
You have to leave space before "%s" inside the scanf statement,so that the '\n character is not stored in ckey to ensure success of comparison.note: ckey must have size 6 or more.
#include <stdio.h>
#include <string.h>
int main(){
char key[] = "april",ckey[6];
printf("Enter the key: ");
scanf(" %5s",ckey);
if(!strcmp(ckey, key)){
printf("Correct.");
}
else{
printf("Wrong.");
}
return 0;
}
you have to check character by character.
try this code :
int main(){
int i = 0 ; int j = 1;
char key[6]="april",ckey[6];
printf("Enter the key: ");
scanf("%s",ckey);
for(i = 0; i < 6; i++){
if(ckey[i] != key[i])
j=0;
}
if(j == 1)
printf(%s,"Correct.");
else
printf(%s,"Wrong.");
return 0;
}
You make several mistakes in array sizing for your keys. Remember, a C string is always terminated by a nul character and you must account for this when you size your arrays to accept such strings.
scanf is unsafe, don't use it. Use fgets instead. A safe use of fgets is:
fgets (buffer, sizeof(buffer), stdin);
The answer to your question is no, it would be better to use strcmp if you want to lexically compare strings in C and that would involve including the header. But even so, this is not adding any other "libraries" since fgets and strcmp are in the same standard C library.
If you must not add any other headers (which makes no sense if this is part of a larger project but makes perfect sense if this is a homework problem) then you can write your own strcmp (we'll call it compare here) and call it from main.
#include <stdio.h>
int compare (const char* src, const char* dst)
{
int ret = 0;
while( ! (ret = *src - *dst) && *dst){
++src, ++dst;
}
if ( ret < 0 )
ret = -1 ;
else if ( ret > 0 )
ret = 1 ;
return( ret );
}
int main(void){
char key[6]="april",ckey[6];
printf("Enter the key: ");
fgets(ckey, sizeof ckey, stdin);
if(!compare(key,ckey)) {
printf("Correct.");
}
else {
printf("Wrong.");
}
return 0;
}
A better use of your time would be to write it using the functions available to you in the standard C library:
#include <stdio.h>
#include <string.h>
int main(void){
char key[6]="april",ckey[6];
printf("Enter the key: ");
fgets(ckey, sizeof ckey, stdin);
if(!strcmp(key,ckey)) {
printf("Correct.");
}
else {
printf("Wrong.");
}
return 0;
}
But even this solution has a flaw. It will accept "aprilaaaa" or any string beginning with "april" as a valid ckey. Can you explain why? How would you fix this?
In the condition of the if statement
if(ckey==key){
there are compared two addresses of the memory areas occupied by the arrays.
So you will always get false because the arrays occupy different memory areas.
If you may not use other standard functions as for example strncmp or memcmp declared in header <string.h> then you can write the following way
#include <stdio.h>
int main( void ){
char key[5]="april",ckey[6];
printf("Enter the key: ");
scanf("%5s",ckey);
size_t i = 0;
while ( i < sizeof( key ) && key[i] == ckey[i] ) ++i;
if( i == sizeof( key ) ){
printf("Correct.");
}
else{
printf("Wrong.");
}
return 0;
}
Instead of scanf it would be better to use fgets. In this case the size of the array ckey must be increased.
This declaration
char key[5]="april";
is totally valid in C though is not valid in C++.:)
I want to print a line similar as following:
====================================
And I need to control the count of the char, and able to specify which char to print.
I don't want to use loop.
Is it possible to do this with a single printf() statement?
#Update
I ask this because I use printf in this way sometimes:
printf("%10s\n", "abc");
So, if printf could do this, then it's possible to do what I ask, I am just not sure ... now I know it can't ...
Ok, I wrote a simple util function to do this:
#include <stdio.h>
void printRepeatChar(char c, int count) {
char cs[count+1];
int i;
for(i=0; i<count; i++)
cs[i] = c;
cs[count] = '\0';
printf("%s\n", cs);
}
int main(int argc, char * argv[]) {
printRepeatChar('-', 6*4);
}
maybe use memset() from string.h instead of the direct loop makes the code shorter, just as in the answers.
And, thank you all for help.
#include <stdio.h>
#include <string.h>
void PrintStuff( char to_print, int length ) {
// adjust buffer size as desired
char buffer[256];
// -1 for null terminator
if( length > sizeof(buffer)-1 ) length = sizeof(buffer)-1;
// fill buffer with desired character
memset( buffer, to_print, length );
// add null terminator
buffer[length] = 0;
// print to output
puts( buffer );
}
int main() {
PrintStuff( '=', 11 );
return 0;
}
http://ideone.com/RjPr83
And to answer the subquestion: no, printf cannot repeat a character as a formatting rule. It can only repeat spaces or 0's when padding.
#include <stdio.h>
#include <string.h>
int main(void) {
char c='=';
char a[20];
memset(a,c,(sizeof(a)-1));
a[19] = '\0';
printf("%s\n",a);
return 0;
}
Dynamic memory allocation and character scanning can be added to this .
I had a code which works fine with the integers
#include<stdio.h>
int main()
{
int i;
int* p[5];
printf("Enter the elements to be shorted");
for(i=0;i<=4;i++)
{
scanf("%d\n",&p[i]);
}
for(i=0;i<=4;i++)
{
printf("entered [%d] integers are = %s",i, p[i]);
}
return 0;
}
produce a output
Enter the strings to be shorted1
2
3
4
5
6
enetered [0] string is = 1
enetered [1] string is = 2
enetered [2] string is = 3
enetered [3] string is = 4
enetered [4] string is = 5
but when i change limne int* p[5] to char* p[5] for using it as array of pointers to string and do the necessary changes in the above code, it produces segmentation fault.I read ian a book that we cant do this as some garbage value will be assigned to the array of pointers to string.So what can be the possible way to implement the above code with array of pointers to string.
what i want to do is get the strings as input from users and store them in array of pointers to string and then get them printed at initial stage.I am trying to code for simplest string shorting.
Make sure you reserve room for the characters of the strings:
char p[5][128];
and also make sure you limit the length when reading, so scanf() doesn't write outside the buffer:
if(scanf("%127s", p[i]) == 1)
{
p[i][127] = '\0'; /* Make sure it's terminated. */
}
First of all, the int array definition is wrong in your first test. it should be
int p[5];
Second you have to allocate memory for each pointer in your array. each element in your array char *p[5]; is a pointer.
You can use directly by scanf
char *p[5];
for(i=0;i<=4;i++)
{
scanf("%ms\n",&p[i]);
}
But this is not portable is available only for gcc>gcc2.7
or you have to allocate memory each time before scanf()
char *p[5];
for(i=0;i<=4;i++)
{
p[i]=calloc(100,1);
scanf("%99s\n",p[i]);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int i;
char *p[5];
printf("Enter the string\n");
for(i=0;i<=4;i++){
char buff[128];
scanf("%127s", buff);
p[i] = strdup(buff);
}
for(i=0;i<=4;i++){
printf("entered [%d] string is = %s\n", i+1, p[i]);
}
for(i=0;i<5;++i) free(p[i]);
return 0;
}
i am new in programming and in stackoverflow that is why i sometime maybe can have simple questions when i code something and want to get input fromthe file`
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int len1=0;
FILE* p;
char a;
char b[10];
p = fopen(argv[1],"r");
while (1)
{
a = fgetc(p);
if(a == ' ') break;
else
{
len1++;
b[len1-1] = a;
}
}
printf("%c\n", b0);
return 0;
}
it gives segmentation fault and what is the reason?
You have a buffer overrun. If you change your while loop to stop after reading ten characters, even if space has not been reached, you should do fine.
Additionally, you are passing a character at b[len1] into printf, and have it interpreted as a pointer. This will segfault no matter what.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int len1=0;
FILE* p;
char a;
char b[10+1]; // <<== need one more byte for the terminator
if (argc != 2)
{
fprintf(stderr, "Need to supply a filename\n");
return (-1);
}
p = fopen(argv[1],"r");
if (p == NULL)
{
fprintf(stderr, "Cannot open file %s\n", argv[1]);
return(-2);
}
while (len1 < 10) // <<== avoid buffer overruns
{
a = fgetc(p);
if(a == ' ') break;
else
{
len1++;
b[len1-1] = a;
}
}
b[len1] = '\0'; // <<== Don't forget to zero-terminate
printf("%s\n", b); // <<== Pass the buffer, not the last character from it
return 0;
}
char b[10] only has 10 elements. len1 is incremented every iteration of an infinite loop. This quickly becomes > 10. Eventually somewhere past 10 you write into some memory you don't have access too. Hence the seg fault.
Instead of the while (1), you should test the loop index against the size of your table b (so 10)
What do you want to do exactly ?
You have two problems
What happens when you read the file and the first 10 characters are not a space? The array b will be esxhausted.
printf is trying to print a string. b[len1] is a character.
There are two logical bugs in your program ::
1.while(1) you are having an non-terminating loop, it will result into stackoverflow.
2. char b[10] here, b is a char array of size 10 i.e. b[0] to b[9], but as in your program len1++ is executing for every iteration, which will access memory beyond b[9].
To overcome these issues use while(len1<10).
How can you code this in C language if the output is like this? I need strings format of the code because our topic is strings.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char my_string[50];
printf("Enter a word:");
scanf("%s", my_string);
printf("Enter a word:");
scanf("%s", my_string);
// Some unknown code here...
// this part is my only problem to solve this.
getch();
}
Output:
Hello -> (user input)
World -> (user input)
HWeolrllod -> (result)
Okay, you need to do some investigating. We don't, as a general rule, do people's homework for them since:
it's cheating.
you'll probably get caught out if you copy verbatim.
it won't help you in the long run at all.
The C library call for user input that you should use is fgets, along the line of:
char buffer[100];
fgets (buffer, sizeof(buffer), stdin);
This will input a string into the character array called buffer.
If you do that with two different buffers, you'll have the strings in memory.
Then you need to create pointers to them and walk through the two strings outputting alternating characters. Pointers are not an easy subject but the following pseudo-code may help:
set p1 to address of first character in string s1
set p1 to address of first character in string s1
while contents of p1 are not end of string marker:
output contents of p1
add 1 to p1 (move to next character)
if contents of p2 are not end of string marker:
output contents of p2
add 1 to p2 (move to next character)
while contents of p2 are not end of string marker:
output contents of p2
add 1 to p2 (move to next character)
Translating that into C will take some work but the algorithm is solid. You just need to be aware that a character pointer can be defined with char *p1;, getting the contents of it is done with *p1 and advancing it is p = p + 1; or p1++;.
Short of writing the code for you (which I'm not going to do), there's probably not much else you need.
void main()
{
char my_string1[50],my_string2[50]; int ptr;
ptr=0;
printf("Enter a word : ");
scanf("%s",my_string1);
printf("enter a word");
scanf("%s",my_string2);
while(my_string1[ptr]!='\0' && my_string2[ptr]!='\0')
{
printf("%c%c",my_string1[ptr],my_string2[ptr]);
ptr++;
}
if(my_string1[ptr]!='\0')
{
while(my_string1[ptr]!='\0')
{ printf("%c",my_string1[ptr]);
ptr++;
}
}
else
{
while(my_string2[ptr]!='\0')
{printf("%c",my_string2[ptr]);
ptr++;
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char my_string1[50],my_string2[50];
int i,l1=1,l2=0;
printf("Enter a word:");
scanf("%s", my_string1);
printf("Enter a word:");
scanf("%s", my_string2);
l1=strlen(my_string1); /* Length of 1st string */
l2=strlen(my_string2); /* Length of 2nd string */
if(l1==l2)
{
for(i=0;i<l1;i++)
{
printf("%c%c",my_string1[i],my_string2[i]);
}
}
else
{
printf("Length of the entered strings do not match");
}
}
This is your required code.
You can see that output needs to be a String containing all chars of User String1 and User String2 one by one...
You can do this like...
//add #include<String.h>
int l1=strlen(s1);
int l2=strlen(s2);
if(l1!=l2)
{
printf("length do not match");
return 0;
}
char ansstr[l1+l2];
int i,j=0,k=0;
for(i=0;i<l1+l2;i=i+2)
{
ansstr[i]=s1[j];
ansstr[i+1]=s2[k];
j++;
k++;``
}
//ansstr is your answer
Ok, here's your code. Come on guys, if he asked here it means he can't solve this.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char str1[] = "abcdefghijklmopq";
char str2[] = "jklm";
int len1 = strlen(str1);
int len2 = strlen(str2);
int c1 = 0, c2 = 0;
int max = (len1 > len2) ? len1 : len2 ;
char *result = malloc(len1 + len2);
for(c1 = 0; c1 <= max; c1++) {
if(c1 < len1)
result[c2++] = str1[c1];
if(c1 < len2)
result[c2++] = str2[c1];
}
result[c2] = 0;
printf("\n%s\n", result);
return 0;
}
Basically the loop picks up a character from str1 and appends it to result. Then it picks a character, which stands in the same position as the first from str2 and appends it to result, just as before. I increment c2 by 2 every time because I'm adding 2 chars to result. I check if c1 is bigger that the length of the strings because I want to copy only the characters in the string without the terminating \0. If you know that your strings have the same length you can omit these ifs.