#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.
Related
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';
}
I am making a text based game, and i am having a big problem with input. Here is a small example of my problem code.
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
}
return 0;
}
So, if you compile/run this, and type in 'abc', it will just take each one, and send it through the loop. What I need it to do is only take the very first character that someone types in, no matter how many they do type in.
And, PS: I have tried it this way, and it does the same thing:
#include <stdio.h>
#include <stdlib.h>
char c[2];
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
scanf("%1s", c);
printf("\nYour input: %c\n", c[0]);
sleep(1);
system("clear");
}
return 0;
}
EDIT: It also adds a space to what ever you type in, I assume it is a \0, but im not sure. Thanks!
When you use scanf, enter a string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character. The string or character by character gets consumed by the scanf but the newline remains in the input buffer, unless you consume that too.
getchar(), on the other hand will not wait for ENTER key, it would read character by character, then your logic.
I think you can add 1 more line to read all the characters that come after the first one until there is a newline character (i.e. the user presses Enter):
while (getchar() != '\n');
Adding to your example, it would be like this:
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
while (getchar() != '\n');
}
return 0;
}
Use getch() which does not wait for a newline.
What i think you look for is something like this code, to save very first character, you can also check if c == '\n' to continue your operation, but i dont know what you want after saving very first character:
int i,c;
char save;
for ( i = 0;(c=getchar())!= EOF ; i++)
{
if ( i == 0)
save = c;
}
You can use fgets(), and extract its first character, like...
char ch[2], c;
fgets(ch, 2, stdin);
c = ch[0];
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);
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;
}