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);
Related
Using the following code:
char *name = malloc(sizeof(char) + 256);
printf("What is your name? ");
scanf("%s", name);
printf("Hello %s. Nice to meet you.\n", name);
A user can enter their name but when they enter a name with a space like Lucas Aardvark, scanf() just cuts off everything after Lucas. How do I make scanf() allow spaces
People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).
Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.
Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Maximum name size + 1. */
#define MAX_NAME_SZ 256
int main(int argC, char *argV[]) {
/* Allocate memory and check if okay. */
char *name = malloc(MAX_NAME_SZ);
if (name == NULL) {
printf("No memory\n");
return 1;
}
/* Ask user for name. */
printf("What is your name? ");
/* Get the name, with size limit. */
fgets(name, MAX_NAME_SZ, stdin);
/* Remove trailing newline, if there. */
if ((strlen(name) > 0) && (name[strlen (name) - 1] == '\n'))
name[strlen (name) - 1] = '\0';
/* Say hello. */
printf("Hello %s. Nice to meet you.\n", name);
/* Free memory and exit. */
free (name);
return 0;
}
Try
char str[11];
scanf("%10[0-9a-zA-Z ]", str);
This example uses an inverted scanset, so scanf keeps taking in values until it encounters a '\n'-- newline, so spaces get saved as well
#include <stdio.h>
int main (int argc, char const *argv[])
{
char name[20];
// get up to buffer size - 1 characters (to account for NULL terminator)
scanf("%19[^\n]", name);
printf("%s\n", name);
return 0;
}
You can use this
char name[20];
scanf("%20[^\n]", name);
Or this
void getText(char *message, char *variable, int size){
printf("\n %s: ", message);
fgets(variable, sizeof(char) * size, stdin);
sscanf(variable, "%[^\n]", variable);
}
char name[20];
getText("Your name", name, 20);
DEMO
Don't use scanf() to read strings without specifying a field width. You should also check the return values for errors:
#include <stdio.h>
#define NAME_MAX 80
#define NAME_MAX_S "80"
int main(void)
{
static char name[NAME_MAX + 1]; // + 1 because of null
if(scanf("%" NAME_MAX_S "[^\n]", name) != 1)
{
fputs("io error or premature end of line\n", stderr);
return 1;
}
printf("Hello %s. Nice to meet you.\n", name);
}
Alternatively, use fgets():
#include <stdio.h>
#define NAME_MAX 80
int main(void)
{
static char name[NAME_MAX + 2]; // + 2 because of newline and null
if(!fgets(name, sizeof(name), stdin))
{
fputs("io error\n", stderr);
return 1;
}
// don't print newline
printf("Hello %.*s. Nice to meet you.\n", strlen(name) - 1, name);
}
getline()
Now part of POSIX, none-the-less.
It also takes care of the buffer allocation problem that you asked about earlier, though you have to take care of freeing the memory.
You can use the fgets() function to read a string or use scanf("%[^\n]s",name); so string reading will terminate upon encountering a newline character.
If someone is still looking, here's what worked for me - to read an arbitrary length of string including spaces.
Thanks to many posters on the web for sharing this simple & elegant solution.
If it works the credit goes to them but any errors are mine.
char *name;
scanf ("%m[^\n]s",&name);
printf ("%s\n",name);
You may use scanf for this purpose with a little trick. Actually, you should allow user input until user hits Enter (\n). This will consider every character, including space. Here is example:
int main()
{
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do
{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
} while (c != '\n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for loop that takes char by char from input stream (till \n) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.
Hope this will help someone!
While you really shouldn't use scanf() for this sort of thing, because there are much better calls such as gets() or getline(), it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: \"%s\"\n\n", s);
return 0;
}
/*reading string which contains spaces*/
#include<stdio.h>
int main()
{
char *c,*p;
scanf("%[^\n]s",c);
p=c; /*since after reading then pointer points to another
location iam using a second pointer to store the base
address*/
printf("%s",p);
return 0;
}
I'm very new to C, any help would be greatly appreciated.
I can't use the <string.h> or <ctype.h> libraries.
This is the code I have:
int main(void)
{
char character;
printf("Introduce characters: ");
scanf(" %c", &character);
printf("\nSize of character: %d", sizeof(character)/sizeof(char));
return 0;
}
This only prints 1 as the size.
I read in another post that the problem was that initializing character by char character; would only let me store 1 single character. So, I modified it to be an array:
int main(void)
{
char character[10];
printf("Introduce maximum 10 characters: ");
scanf(" %s", character);
printf("\nSize of character: %d", sizeof(character)/sizeof(char));
return 0;
}
The problem now is that by doing character[10], it prints out that the size is 10. How would I go about fixing this?
sizeof(character)/sizeof(char) gives you the size of the array you declared, not the size of what the user has entered.
sizeof(character) gives the size of the entire array in bytes
sizeof(char) gives the size of a single character in bytes
So, when you do sizeof(character)/sizeof(char), you get the actual size (i.e. number of elements) of your array. What you are trying to achieve can be done with strlen(). But since you can't use <string.h>, you can write it yourself:
int strlen2(char *s)
{
int size;
for (size = 0; s[size]; size++)
;
return size;
}
Then use it like:
#include <stdio.h>
int main(void)
{
char character[10];
printf("Introduce maximum 10 characters: ");
scanf("%s", character);
printf("\nSize of character: %d", strlen2(character));
}
strlen2() counts the number of characters of your string, it stops counting when it encounters the first \0 character (null terminator).
Avoid using scanf() to read input
Your code is prone to bugs. If the user enters a string more than 9 characters long (don't forget the \0 is added at the end of your string), you'll get a buffer overflow, because character is only supposed to contain 10 characters. You would want to limit the number of characters read into your string:
scanf("%9s", character); // Read only the first 9 characters and ignore the rest
Moreover, scanf() is used to parse input, not to actually read it. Use fgets() instead:
#include <stdio.h>
#include <string.h> // for strcspn()
int main(void)
{
char character[10];
printf("Introduce maximum 10 characters: ");
if(!fgets(character, 10, stdin)) {
fprintf(stderr, "Error reading input.\n");
return 1;
}
character[strcspn(character, "\n")] = '\0'; // fgets() reads also `\n` so make sure to null-terminate the string
printf("\nSize of character: %zu", strlen(character));
}
fgets() accepts three arguments:
The first one is the array in which you want to store user input
The second one is the size of your array
The third one is the file stream you want to read from
It returns NULL on failure so you should check that as well.
Well if you can't use any headers, maybe you can create a custom strlen() function.
strlen() pretty much counts all character until the '\0' character is found. '\0' is used to signify the end of string and is automatically appended by scanf("%s",...).
#include <stdio.h>
size_t ms_length(const char *s)
{
size_t i = 0;
for (; s[i] != '\0'; i++)
;
return i;
}
int main(void)
{
char *str = "hello";
printf("%zu\n", ms_length(str));
return 0;
}
And if you want to be pedantic, you might even want to check the return value of scanf(), for input errors and also apply a limit to the character to be read to avoid a buffer overflow.
if (scanf(" %9s", character) != 1) /* 9 characters + 1 reserved for \0 */
{
/* handle error */
return 1;
}
I have the following program that takes as input the batsman names and their scores and prints the batsman with the highest score. I have written the following algorithm and it works. But the only problem I am facing is that, the newline character is getting displayed on the screen after the input has been gotten from the user.
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
int main()
{
int n;
char bat[100],maxs[100];
int score,max=INT_MIN;
scanf("%d",&n);
while(n--)
{
scanf("%99[^,],%d",bat,&score);
if(score>max)
{
max=score;
strcpy(maxs, bat);
}
}
printf("%s",maxs);
}
I have no clue of where the newline is coming from? Please see the output shown below. Any help is appreciated.
Imagine the following program:
#include <stdio.h>
int main() {
int a;
scanf("%d", &a);
char string[100];
scanf("%99[^,]", string);
printf("-----\n");
printf("%s", string);
}
Now execution could look like:
10 # %d scans 10 and leaves the newline in input
string, # then %99[^,] reads from the newline including it up until a ,
-----
string
How can I resolve this so that the newline is removed?
Read the newline. A space character in scanf ignores all whitespace charactesrs.
scanf(" %99[^,]", string);
You could ignore a single newline character, if you want to be "exact":
scanf("%*1[\n]%99[^,]", string);
You're getting a newline there because scanf() requires you to hit enter to proceed. This enter then gets stored in the string as well. You could remove newlines at the end or beginning with something like this (source here):
void remove_newline_ch(char *line)
{
int new_line = strlen(line) -1;
if (line[new_line] == '\n')
line[new_line] = '\0';
}
#include <stdio.h>
#include <string.h>
int main() {
char a;
char s[100];
char sen[100];
scanf("%c",&a); // take character
printf("%c",a); //print character
scanf("%s",s); //take input as a word
printf("\n%s",s); //print the word
if((gets(sen))=='\n')
gets(sen);// take input as a string
puts(sen); //print that string
}
As gets() takes input from buffer so it will take '\n' as input after that another gets() command should work but that is not working. It doesn't take any input. Why?
gets(sen) returns sen, which is the address of the char array.
Therefore, what you are trying to do should be
if(strcmp(gets(sen), "\n") == 0)
gets(sen);// take input as a string
However, this is error-prone because sen can be a space with a newline, which is not "\n" or so.
I have program that asks to enter a string (mystring) and a char (ch). Then it deletes all entered chars (ch) from the string (mystring). For example "abcabc" and char 'a' then the result shoud be "bcbc".
-When I use scanf the program works nicely if the string does not have spaces. If I enter "abc abc abc" It reads and processes only the first 3 letters (until space).
Then I was advised to use gets(mystr); because it can read all the stirng. But when I use gets the result is the same as the input string and nothing happens.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
//gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
scanf("%c",&ch);
scanf("%c",&ch);
That second scanf is your problem. It's picking up the new-line character that you enter after the letter you want to remove (and overwrites the previous value of ch).
Get rid of it.
Please note, as the man page says:
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.
hmm - not sure what the problem is - use getstr, but not scanf for the string, and it works for me in visual studio
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
// scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
Use this one:
char temp[2];
scanf("%1s",temp);
ch = temp[0];
and use gets
scanf when used with chars has some problems (it gets the "old" new line). Here we "cheat" a little and we use scanf to get a string that can have up to one character. A string of 1 character clearly needs a second character for the terminator, so an array of 2 characters.
Be aware that using a scanf for the character to search, you won't be able to insert the space character.
Note that gets is an "evil" function. You can easily do buffer overruns using it (it doesn't check that the buffer is big enough). The "right" way to do it is normally: fgets(mystr, N, stdin); (the "file" variant of gets has a maximum number of characters that can be read and will append a \0 at the end). Note that if you insert 150 characters in a fgets, 99 will go to your string (because you gave 100 of max size), 1x \0 will be appended and the other characters will remain in the buffer "ready" for the next scanf/gets/fgets... (to test it, reduce the buffer to a smaller value, like 5 characters, and do some tests)
You can use fgets() as suggested by xanatos with a small hack, so you can reliably handle return characters. Just change the '\n' to '\0' in the string obtained using fgets.
And in your program, you forgot to terminate the new string with a '\0'.
So here's the code you're looking for.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int main(int argc,char **argv){
char string[N],str1[N];
char ch;
int i,k = 0;
fgets(string,N,stdin);
string[strlen(string)-1] = '\0';
scanf("%c",&ch);
printf("\n%s , %c",string,ch);
for (i=0;i<=strlen(string);i++)
if(string[i] != ch)
str1[k++] = string[i];
str1[k] = '\0';
printf("\n%s , %s\n",string,str1);
return 0;
}