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;
}
Related
I was trying to input a string of characters and only output the last and the first character respectively. Below is the code I'm using.
#include<stdio.h>
int main(){
for(int i=0;i<3;i++){
int n; // length of the string
char string[101];
scanf("%d %s", &n, &string);
fflush(stdin); // sometimes I also use getchar();
printf("%c%c", string[n+1], string[0]);
}
printf("\n");
return 0;
}
I'm using for loop because i wanted to input the string 3 times, but when I ran the code the input isn't what I expected. If I input e.g.
5 abcde
output
a //there's space before the a
can you help me tell where I've gone wrong?
input:
5 abcde
6 qwerty
3 ijk
excpeted output:
ea
yq
ki
Few problems in your code:
In this statement
scanf("%d %s", &n, &string);
you don't need to give & operator with string. An array name, when used in an expression, converts to pointer to first element (there are few exceptions to this rule). Also, the size of string array is 101 characters but if you provide input more than 101 characters, the scanf() end up accessing string array beyond its size. You should restrict the scanf() to not to read more than 100 characters in string array when input size is more than that. (keep the remain one character space is for null terminating character that scanf() adds). For this, you can provide width modifier in the format specifier - %100s.
You are not validating the string length input against the input string from user. What happen, if the input string length is greater than or less than the actual length of input string!
fflush(stdin) is undefined behaviour because, as per standard, fflush can only be used with output streams.
I was trying to input a string of characters and only output the last and the first character respectively.
For this, you don't need to take the length of the string as input from user. Use standard library function - strlen(). This will also prevent your program from the problems that can occur due to erroneous length input from user, if that is not validated properly.
Putting these altogether, you can do:
#include <stdio.h>
#include <string.h>
int main (void) {
for (int i = 0; i < 3 ; i++) {
char string[101];
printf ("Enter string:\n");
scanf("%100s", string);
printf("Last character: %c, First character: %c\n", string[strlen(string) - 1], string[0]);
int c;
/*discard the extra characters, if any*/
/*For e.g. if user input is very long this will discard the input beyond 100 characters */
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
}
return 0;
}
Note that, scanf(%<width>s, ......) reads up to width or until the first whitespace character, whichever appears first. If you want to include the spaces in input, you can use the appropriate conversion specifier in scanf() or a better alternative is to use fgets() for input from user.
Line 11: string[n+1] -> string[n-1]
I am having a c program which print letter by letter of the word. I referred this program from this link
https://www.tutorialgateway.org/c-program-to-print-characters-in-a-string/. If I run this program in online c compiler this gives the exact result, but not working in turbo c++
#include <stdio.h>
int main()
{
char str[100];
printf("\n Please Enter any String : ");
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++)
{
printf("The Character at %d Index Position = %c \n", i, str[i]);
}
return 0;
}
This program doesn't through any error, but I don't know why this program doesn't print the result.
Try fgets(str, 100, stdin) instead of scanf(). This is the normal way to read a line into a buffer. When I used scanf() I only got part of the output because it will stop reading a string at a space.
IDK what is your output, but here is mine:
Please Enter any String : Hell got loose
The Character at 0 Index Position = H
The Character at 1 Index Position = e
The Character at 2 Index Position = l
The Character at 3 Index Position = l
This is normal, due to this:
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 character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
this is taken from scanf.
EDIT:
Just for the fun, you can do this using scanf
scanf("%[^\n]",str);
this will replace \n newline with '\0'.
NOTE: #Joshua's answer is safer, if you want to know why just google why I shouldn't use scanf()
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;
}
I'm writing a program to find the location of a certain character in a string using strchr. When using fgets to input the string from the user, the program does not execute properly.
However when using gets everything works fine.
Code that works using gets():
#include <stdio.h>
#include <string.h>
int main() {
char let;
char input[50];
char *ptr;
printf("what is the string that you would like to check?\n");
gets(input);
printf("what is the character that you would like to find?\n");
let = getchar();
printf("in string \"%s\"...\n", input);
ptr = strchr(input, let);
while (ptr != NULL) {
printf("the letter %c was found at character %d\n", let, ptr - input + 1);
ptr = strchr(ptr + 1, let);
}
return 0;
}
Output:
what is the string that you would like to check?
what is the character that you would like to find?
in string "why is the world when wondering"...
the letter w was found at character 1
the letter w was found at character 12
the letter w was found at character 18
the letter w was found at character 23
Code that does not work usgin fgets():
#include <stdio.h>
#include <string.h>
int main() {
char let;
char input[50];
char *ptr;
printf("what is the string that you would like to check?\n");
fgets(input, 16, stdin);
printf("what is the character that you would like to find?\n");
let = getchar();
printf("in string \"%s\"...\n", input);
ptr = strchr(input, let);
while (ptr != NULL) {
printf("the character is found at %d \n", ptr - input + 1);
ptr = strchr(ptr + 1, let);
}
return 0;
}
Output:
what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...
Change
fgets(input, 16, stdin)
to
fgets(input, sizeof(input), stdin)
When you pass an argument of 16 to fgets() you are instructing it to read no more than 15 characters. Why?
From the fgets() manpage:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.
If you provide more than size -1 characters, the remaining characters are left in the input buffer.
Then when the program subsequently calls
let = getchar();
let is assigned whatever the next character in the input buffer is - without even waiting for you to type anything else. It then searches for this character in the string you provided - but in the example you provided doesn't find it.
In the first code snippet the call
gets (input);
does not restrict the number of characters the user can input. Take into account that the function gets is not supported by the C Standard and is unsafe.
In the second code snippet you declared the variable input as
char input[50];
So it is more natural to call fgets the following way
fgets (input,sizeof( input ),stdin );
instead of
fgets (input,16,stdin);
The standard function getchar reads any character including white spaces.
So instead it it is much better to use
scanf( " %c", &let );
Otherwise getchar can read any character (including for example the new line character) leaved in the input buffer. While the call of scanf will skip any white space character.
I am trying to write a function that gets a string of letters, either capital letters or small letters, and prints 2 other strings, one with only the capitals, and one only with the small letters. for example:
input: AaBbCcDD
Output: Capital string is ABCDD, non capital is abc
My code is not working correctly, it seems to skip over the last letter. To test it, I wrote the following code:
int length;
printf("Please enter length of string\n");
scanf("%d",&length);
string=create_string(length);
scan_string(string,length);
printf("The string entered is: \n");
print_string(string,length);
Where create_string is:
char* create_string(int size)
{
char* string;
string=(char*)malloc(size*sizeof(char));
return string;
}
Scan string is:
void scan_string(char* string, int size)
{
int i;
printf("Please enter %d characters\n",size);
for(i=0;i<size;i++)
scanf("%c",string+i);
}
And print string is
void print_string(char* string,int size)
{
int i;
for(i=0;i<size;i++)
printf("%c ",*(string+i));
}
When I try even just to print the string I entered, this is what I get, after I input aaAAB
The output is a a A A.
it skipped over the B.
The problem is with the scanf that reads characters using %c: it follows the scanf that reads the length using %d, which leaves an extra '\n' character in the buffer before the first character that you get.
If you modify the output to put quotes around your characters, you would actually see the \n:
void print_string(char* string,int size)
{
int i;
for(i=0;i<size;i++)
printf("'%c' ",*(string+i));
}
This prints
'
' 'a' 'a' 'A' 'A'
(demo on ideone)
You can change your first scanf to read '\n' as below. This will read the extra '\n'
scanf("%d\n", &length);
I think your code is unnecessarily elaborated. To read a string the function fget() with parameter stdin is a simpler choice.
For example, I wuold not ask to the user for the length of the string.
Perhaps it is better to use a buffer with fixed length, and to restrit the user to enter a string with the length less than which you have been previously stipulated.
#define MAXLEN 1000
char buffer[MAXLEN] = "";
fgets(buffer, MAXLEN, stdin);
If the user attempts to enter a string with more than MAXLEN characters, it would be necessary to handle the end-of-line in some way, but I think this is out of topic.
So, in general, let us suppose that MAXLEN is large enough such that buffer contains the \n mark.
Now, a call to your function print_string() can be done.
However, it would be better to do this:
printf("%s", buffer);
I think that you probably need to take in account the C convention for strings: a string is a char array whose last element is marked with the character '\0' (null character, having always code 0).
Even if you want to insist in your approach, I think that scanf() is a bad choice to read individual characters. it is more easy to use getchar(), instead.
By using scanf() you have to broke your brain figurating out all the stuff around the behaviour of scanf(), or how to handle the read of characters, and so on.
However, getchar() reads one char at a time, and that's (almost) all. (Actually, the console commonly not returns the control to the user until an end-of-line \n has been read).
string[i] = getchar();
The problem is because the scanf does not eat the "\n". Hence there is still one '\n' remaining at your first input. This will be counted at the next scanf.
Try to put an additional getchar() right after your first scanf.
printf("Please enter length of string\n");
scanf("%d",&length);
getchar(); // remove '\n'
string=create_string(length);