Storing the string in run time in C - c

I am trying to store a string at run time.
#include<stdio.h>
#include<string.h>
void main()
{
char string[4];
printf("Enter the String\n");
scanf("%s", &string[4]);
printf("The String entered is %s\t", string);
}
Output:
Enter the String
ABCD
The String entered is
But Actual Expected output should be The String entered is ABCD. Why i am getting Empty.

&string[4] is the address of the end of the the array, not the start of it.
Change it to
scanf("%s", string);
And if you want to hold 4 chars, you need to make it at least with size = 5 (last one is the null termination character):
char string[5];

&string[4] is one past the end of the array just use string to refer to the beginning of the array.
you also should leave space at the end to put a null termination character.

Related

How to make bash prompt start at new line in vs code?

I am currently using ubuntu 21.04. I was running a C code on my Visual Studio Code but my bash prompt is starting from the end of my output. I want to start bash prompt from new line.
CODE:
#include<stdio.h>
void main()
{
int i=0;
char str1[20],str2[20];
printf("Enter a string: ");
scanf("%s",str1);
while (str1[i]!='\0')
{
str2[i]=str1[i];
i++;
}
printf("The copy of string is: %s",str2);
}
OUTPUT:
Your source code has an error, the result string is not NULL terminated. You must copy the terminated '\0' in str2. A possible fix is:
#include<stdio.h>
void main()
{
int i=0;
char str1[20],str2[20];
printf("Enter a string: ");
scanf("%s",str1);
do
{
str2[i]=str1[i];
} while (str1[i++]!='\0');
printf("The copy of string is: %s",str2);
}
BUT the latter is still unsecure: check the maximum value for i to avoid an overflow in str2.
Then, the way it works under Ubuntu is consistent: if you don't have a terminating newline in the string, the newline will no be displayed. Hence, the following prompt from the shell is displayed at the last position of the cursor.
If you want an new line in the resulting string, either you add it in the printf() format or you get it in the source string with a fgets() instead of a scanf() to get the return typed by the operator into str1 as explained in the manual:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF
or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the
buffer.
Here is an usage example:
#include<stdio.h>
void main()
{
int i=0;
char str1[20],str2[20];
printf("Enter a string: ");
fgets(str1, sizeof(str1), stdin);
do
{
str2[i]=str1[i];
} while (str1[i++]!='\0');
printf("The copy of string is: %s",str2);
}
Example:
$ gcc scan.c -o scan
$ ./scan
Enter a string: qwerty
The copy of string is: qwerty
$

Inputting a string and copying its value to a second string gives incorrect results in c

In this program, i am trying to read a string str from the standard input stdin using the
function fgets, copy it into another string called copy, and then display
the copied string and its size.
int main(){
char str[10];
char copy[10];
printf("length of str: %ld \n" ,strlen(str));
puts("enter characters:");
fgets(str,strlen(str), stdin);
strcpy(copy,str);
printf("the copy string: ");
puts(copy);
printf("after copy: the size - %zu \n",strlen(copy));
}
But when i run it with a test string ,for example randomString, i get
length of str: 2
enter characters:
randomString
the copy string: r
after copy: the size - 1
I don't understand why in the beginning it shows the length of the original string str as 2 or why only the first character of the inputted string is copied to the second string.What changes should be made to the program so that it successfully copies the inputted string to string copy?
The problem comes from the fact that str is not initializated by the ti,e you first try to use it. strlen() counts all the characters present in the array before the null termination. In you example, str clearly contains a couple of random characters followed by a 0.
On the other side, fgets() takes as argument the number of character to be read, includind the null character at the end of a string. This means that, if your str contains two random characters before the null character, strlen() return 2 and your fgets() can only read 1 character total.
To fix this, just change strlen() by sizeof() to obtain the size of the array containing your string instead of the length of the string inside (of which you dont know the content at that stage).
int main(){
char str[10];
char copy[10];
printf("length of str: %ld \n", sizeof(str));
puts("enter characters:");
fgets(str, sizeof(str), stdin);
strcpy(copy,str);
printf("the copy string: ");
puts(copy);
printf("after copy: the size - %zu \n",strlen(copy));
}

User string input to go until \0 in c [duplicate]

This question already has answers here:
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 5 years ago.
I am trying to simply get a user input string. The string is saved (scanf) when the person hits enter or the string hits the NULL character. Yet, when I run my program, and type in the string, it continues input until I type \n or \0 (whichever I have in my if statement. Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MSL 30
char intersperse(char);
char widen_stars(char);
int main(int argc, char *argv[])
{
char *p, *q, *str1[MSL], *str2[MSL];
if(str1[MSL+1] != '\0'){
printf("Please enter a string of maximum 30 characters: ");
scanf("%s\n", str1[MSL]);
}
printf("%s\n", str1[MSL]);
}
This is by no means finished code, i'm just in the process of writing my program when I snagged this annoying bug. The +1 on my MSL is to make sure the NULL character is read so my string doesn't yell at me, idk if it's necessary, but it's a precaution. Thank you answerers.
There are various problems with your code, not just a simple bug. I'll try to describe some of them here.
Turn on compiler warnings. For example, if your array is size 30, there is no element at index 30 (indexes would go from 0 to 29). Your compiler could have warned you about that and other problems.
Store a string in a char array or pointer, but not in a char pointers array. When you wrote:
char *str1[MSL]
You are creating an array of pointers to char, or an array of strings. However, since you're dealing with pointers to char as strings, you'd need to allocate space for them yourself. That's another concept. You probably meant to write an array of char like this:
char str1[MSL]
char *p, *q, str1[MSL], str2[MSL]; /* in your declaration */
Enter at maximum 29 characters. If your string holds 30 char, and you need 1 to mark the null at the end, you've got 29 remaining usable chars. Or… change MSL to 31.
Consider dropping the \n from your scanf format. It will make it read all whitespace (which is what \n represents in a format) waiting for the next non-whitespace. Thus, the input somestring<enter> for example won't be sent directly to your program until the next non-whitespace or EOF.
Give scanf an address. That could be just the array name (which translates to the first element address) or a pointer if you were working with them.
scanf("%s", str1);
scanf("%s", strptr); /* strptr is a char pointer pointing
to previously allocated space */
You can limit the length of what scanf reads. To be safe:
scanf("%29s", str1);
Don't use uninitialised data in comparisons. When you wrote if(str1[MSL+1] != '\0'), what did you expect str1 to contain if you had never stored anything yet?
int
main(int argc, char **argv)
{
char *p, *q, str1[31], str2[31]; /* a lot of unused variables */
printf("Please enter a string of maximum 30 characters: ");
scanf("%30s", str1);
printf("%s\n", str1);
return 0;
}

How do I allow spaces to be read during execution?

The program is to compare the string but however there's a problem with the spacing when I execute it. As I input the first string with spacing, the program just jump to comparing the strings, not allowing me to input the second string as follows:
>>"Enter first string":
"Hello Hey"
">>Enter second string:"
">>First string is more than the second string."
Here is my code:
#include<stdio.h>
#include<string.h>
int main (void) {
int result; //store results
char input1[50];
char input2[50];
printf("Enter first string:\n");
scanf("%[^\n]s",input1);
printf("Enter second string:\n");
scanf("%[^\n]s",input2);
result = strcmp(input1, input2);
if (result==0)
printf("First string is equal to second string\n");
if (result>0)
printf("First string is greater than second string\n");
if (result<0)
printf("First string is less than the second string\n");
return 0;
}
Add spaces:
scanf(" %[^\n]s",input1);
scanf(" %[^\n]s",input2);
It will consume all the white spaces encountered in previous inputs.
When you enter any input, you also enter a new line character (white space) with your input. And that newline character is being read by second scanf in your code.
The Question:
How do I allow spaces to be read during execution? (the question)
You are already doing it using [^\n] in scanf("%[^\n]s",input1); which means to read the input until a new line (\n) is encountered. Also, not that \n itself doesn't get read in this way.
Output:
Enter first string:
Strings in C
Enter second string:
Strings in C
First string is equal to second string
I think you can do it with the stdlib.h with this function:
gets(input1);
gets(input2);
For sure, the POSIX way will work, you can use read to get the line from stdin:
read(STDIN_FILENO, input1, 50)

concatenating strings using malloc

This is a program to concatenate strings using malloc
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char *sconcat(char *ptr1,char *ptr2);
void main()
{
char string1[20],string2[20],*ptr;
clrscr();
printf("enter string 1: ");
gets(string1);
printf("enter string 2: ");
gets(string2);
ptr=sconcat(string1,string2);
printf("output string : %s",ptr);
getch();
}
char *sconcat(char *ptr1,char *ptr2)
{
int len1,len2,i,j;
char *ptr3;
len1=strlen(ptr1);
len2=strlen(ptr2);
ptr3=(char *)malloc((len1+len2+1)*sizeof(char));
for(i=0;ptr1[i]!='\0';i++)
ptr3[i]=ptr1[i];
j=i;i=0;
for(;ptr2[j]!='\0';j++,i++)
ptr3[j]=ptr2[i];
ptr3[j]='\0';
return(ptr3);
}
output:
enter string 1 : this program does
enter string 2 : not give output
output string : this program does
What correction is needed to concatenate strings. When I use char string1[20],string2[20],*ptr; after void main(),
output:
enter string 1 : is this
enter string 2 : correct ?
output string : correct? ?
The test in your second for loop is incorrect; it should be ptr2[i] != '\0', not ptr2[j] != '\0'.
Several remarks on the code:
Don't cast the return value of malloc.
sizeof(char) is 1 by definition, so multiplying by sizeof(char) only makes the code harder to read.
Declare the parameters of sconcat as const char *, since they're not modifying the strings they receive.
malloc can return NULL; you must handle that case in your program, for example by displaying an error message and exiting.
gets is unsafe and will crash your program if the user enters more characters than were allocated. Replace gets(string) with fgets(string, sizeof(string), stdin), and getting rid of the trailing newline.
clrscr() and getch(), as well as the infamous <conio.h> header, are not standard C and are non-portable; avoid them in simple programs like this one.
You can more simply use strcat
printf("enter string 1: ");
gets(string1);
printf("enter string 2: ");
gets(string2);
strcat(string1,string2);
It would, however, change string1 so you might want to use strcpy too (to copy string1 to another string and then return it).

Resources