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

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
$

Related

Print a middle character of a string

I must write a program in C that can print the middle letter of the string you entered. Spaces () are also calculated, and the number of characters must be odd.
Ex. Input
Hi sussie
--> 9 characters, including space
The output should be s.
I have tried this:
#include <stdio.h>
#include<string.h>
char x[100];
int main(void)
{
printf("Hello World\n");
scanf("%c\n",&x);
long int i = (strlen(x)-1)/2;
printf("the middle letter of the word is %c\n",x[i]);
return 0;
}
and the output always shows the first letter of the word I have entered.
You're only reading the first character from stdin (and incorrectly; you shouldn't be using &).
If you must use scanf, you should use this format:
scanf("%99[^\n]", x);
This is safe and doesn't read past the buffer.
Note that %s wouldn't work here. %s causes scanf to interpret whitespace as the end of the string.
A much better, safer, and easier solution would be to use fgets instead of scanf; fgets is safer and it doesn't require you to change a format string when you change the size of your array:
fgets(x, sizeof(x)-1, stdin);
This eliminates any possible issues with whitespace or buffer overflow.
int main()
{
char arr[1024];
char a;
int i,counter=0;
printf("enter string :: ");
fgets(arr,sizeof(arr),stdin);
for(i=0;i<strlen(arr);i++)
counter++;
for(i=0;i<strlen(arr);i++)
{
if(i==(counter/2))
printf("%c\n",arr[i]);
}
return 0;
}

Calculate length of string without using strlen() function

Having a doubt regarding a very simple C code. I wrote a code to calculate the length of a string without using the strlen function. The code below works correctly if i enter a string with no spaces in between. But if i enter a string like "My name is ---", the length shown is the length of the word before the first white space, which in the example, would be 2. Why is that? Aren't white space and null character two different characters? Please guide me as to how i can change the code so that the entire string length is returned?
char s[1000];
int length = 0;
printf ("Enter string : ");
scanf ("%s", s);
for (int i = 0; s[i] != '\0'; i++)
{
length++;
}
printf ("Length of given string : %d", length);
It is because scanf with %s reads until it finds white space.
from man scanf
Matches a sequence of non-white-space characters; the next pointer
must be a pointer to character array that is long enough to hold the
input sequence and the terminating null byte ('\0'), which is added
automatically. The input string stops at white space or at the maximum
field width, whichever occurs first.
If you want read until \n including white space you can do as below.
scanf("%999[^\n]", s);
Or you could use fgets.
scanf reads the data until "\0" or "\20". So use "fgets" method which reads the data until "\n" (next line) with "stdin",
Example Program:
#include <stdio.h>
int main() {
char s[100];
printf("Input String: ");
fgets(s, sizeof(s), stdin);
printf("\nLength of the string is = %d", printf("%s"), s);
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)

Storing the string in run time in 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.

Reading string from input with space character? [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 4 years ago.
I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE.
What I'm trying to do is reading a string (like "Barack Obama") and put it in a variable:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Your Name is: %s", name);
return 0;
}
Output:
Enter your name: Barack Obama
Your Name is: Barack
How can I make the program read the whole name?
Use:
fgets (name, 100, stdin);
100 is the max length of the buffer. You should adjust it as per your need.
Use:
scanf ("%[^\n]%*c", name);
The [] is the scanset character. [^\n] tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer (which is not read), and the * indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.
Read here about the scanset and the assignment suppression operators.
Note you can also use gets but ....
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
Try this:
scanf("%[^\n]s",name);
\n just sets the delimiter for the scanned string.
Here is an example of how you can get input containing spaces by using the fgets function.
#include <stdio.h>
int main()
{
char name[100];
printf("Enter your name: ");
fgets(name, 100, stdin);
printf("Your Name is: %s", name);
return 0;
}
scanf(" %[^\t\n]s",&str);
str is the variable in which you are getting the string from.
The correct answer is this:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
// pay attention to the space in front of the %
//that do all the trick
scanf(" %[^\n]s", name);
printf("Your Name is: %s", name);
return 0;
}
That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.
NOTE: When using fgets(), the last character in the array will be '\n' at times when you use fgets() for small inputs in CLI (command line interpreter) , as you end the string with 'Enter'. So when you print the string the compiler will always go to the next line when printing the string. If you want the input string to have null terminated string like behavior, use this simple hack.
#include<stdio.h>
int main()
{
int i,size;
char a[100];
fgets(a,100,stdin);;
size = strlen(a);
a[size-1]='\0';
return 0;
}
Update: Updated with help from other users.
#include <stdio.h>
// read a line into str, return length
int read_line(char str[]) {
int c, i=0;
c = getchar();
while (c != '\n' && c != EOF) {
str[i] = c;
c = getchar();
i++;
}
str[i] = '\0';
return i;
}
Using this code you can take input till pressing enter of your keyboard.
char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
scanf("%c ", &ch[i]);
}
While the above mentioned methods do work, but each one has it's own kind of problems.
You can use getline() or getdelim(), if you are using posix supported platform.
If you are using windows and minigw as your compiler, then it should be available.
getline() is defined as :
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
In order to take input, first you need to create a pointer to char type.
#include <stdio.h>
#include<stdlib.h>
// s is a pointer to char type.
char *s;
// size is of size_t type, this number varies based on your guess of
// how long the input is, even if the number is small, it isn't going
// to be a problem
size_t size = 10;
int main(){
// allocate s with the necessary memory needed, +1 is added
// as its input also contains, /n character at the end.
s = (char *)malloc(size+1);
getline(&s,&size,stdin);
printf("%s",s);
return 0;
}
Sample Input:Hello world to the world!
Output:Hello world to the world!\n
One thing to notice here is, even though allocated memory for s is 11 bytes,
where as input size is 26 bytes, getline reallocates s using realloc().
So it doesn't matter how long your input is.
size is updated with no.of bytes read, as per above sample input size will be 27.
getline() also considers \n as input.So your 's' will hold '\n' at the end.
There is also more generic version of getline(), which is getdelim(), which takes one more extra argument, that is delimiter.
getdelim() is defined as:
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
Linux man page
If you need to read more than one line, need to clear buffer. Example:
int n;
scanf("%d", &n);
char str[1001];
char temp;
scanf("%c",&temp); // temp statement to clear buffer
scanf("%[^\n]",str);
"%s" will read the input until whitespace is reached.
gets might be a good place to start if you want to read a line (i.e. all characters including whitespace until a newline character is reached).
"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;
#include <stdio.h>
int main()
{
printf("Enter your name\n");
char a[80];
gets(a);
printf("Your name is %s\n", a);
return 0;
}
scanf("%s",name);
use & with scanf input

Resources