get and check Strings in c language - c

I tried to write program that scan a string from user and check it what the user input and if it is true do somthing and if it's not do somthing else.
the code i wrote is like this:
#include<stdio.h>
#include<conio.h>
int main()
{
char string[20];
printf("Enter a sentence : ");
scanf("%s",&string);
if(strcmp(string,"what's up")==0)
printf("\nNothing special.");
else
printf("\nYou didn't enter correct sentence.");
getch();
return 0;
}
but it doesn't work correct.I think because the program can't recognize the space when it want to scan.What should i do?(I'm new to c,so please explain what did you do.)

%s format specifier can't be used to scan a string with space.
You need to use fgets()
size_t n;
fgets(string,sizeof(string),stdin);
n = strlen(string);
if(n>0 && string[n-1] == '\n')
string[n-1] = '\0';
PS: fgets() comes with a newline character.So you need to gently remove it as shown above

you can still use scanf but like this :
#include<stdio.h>
#include<conio.h>
int main()
{
char string[20];
printf("Enter a sentence : ");
scanf(" %[^\n]s",string);
if(strcmp(string,"what's up")==0)
printf("\nNothing special.");
else
printf("\nYou didn't enter correct sentence.");
getch();
return 0;
}
To prevent buffer overflow,you can write scanf(" %19[^\n]s",string);

you can use the getline1() function to get the entire line as shown below:
/* getline1: read a line into s, return length*/
int getline1(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
lim specifies the maximum length of the line.

Related

Making sure the input is a charachter

This might be a rookie question, but I need to make sure that the input given by the user is of data type char [%c] or a string [%s].
If it were an integer, I would just do something like this:
int data, x;
do {
printf("Please enter a number: ");
x = scanf(" %d", &data);
getchar();
} while(x!=1);
So I was wondering if there's a similar way to do this, if the input is supposed to be a string or a character. Thanks, Any help would be appreciated!
Avoid to use %c in scanf() because some unexpected character like \r\n will be input.
You can use a char[2] to receive a single character. An \0 will be filled after your string to represent the end of string, so the length of array must be bigger than 1.
An example:
#include <stdio.h>
int main()
{
char data[2];
scanf("%1s", data);
if (data[0] >= 'a' && data[0] <= 'z') // custom your constraint here
{
// legal
printf("legal: %s", data);
}
else
{
// illegal
printf("illegal: %s", data);
}
return 0;
}
While I input b, the data will be "b\0".
part of the answer is if you just want to read only alphabet you can use below.
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
do {
printf("enter a char:");
scanf(" %c",&ch);
}while(!isalpha(ch));
printf("%c",ch);
return 0;
}
Update 1:
Just for the completeness and for the FUN part of the programing, have added code here.
This works well (not tested robustly, you can do if you need to) for the single char input or for a string of length 9.
Remember to type the EOF after input is entered in case length of input is < 9.
and read EOF behavior on same line and new line.
#include <stdio.h>
#include <ctype.h>
#define LEN 10
int main()
{
char ch;
char str[LEN] = {0};
int i = 0;
int ret;
printf("enter a char or string(len = 9) and press EOF if len < 9\n");
do {
if(1== (ret = scanf(" %c",&ch)))
{
if(isalpha(ch))
str[i++] = ch;
}
else
printf("scanf:Error (%d)\n", ret);
}while(ret != EOF && ( !isalpha(ch) || i < LEN-1));
str[i] = '\0';
printf("str is %s\n",str);
return 0;
}

Unable to store any value in array

I am unable to put the value in the first element of the array. It's always asking to put the value in array second element.
#include<stdio.h>
#include<string.h>
int main(void)
{
int a, i;
char names[50][50];
printf("\nEnter the number of names you want :");
scanf("%d", &a);
for(i = 0; i < a; i++)
{
printf("\n%d name :", i);
gets(names[i]);
}
printf("\nThe required name lists :");
for(int i = 0; i < a; i++)
{
printf("\n%d name :", i+1);
puts(names[i]);
}
return 0;
}
As scanf leaves behind a dangling newline character \n it causes the gets(Use fgets) to not wait for the input from the user. Try flushing the input buffer by using getchar.
Update: Added mechanism to remove the trailing \n registered by the fgets
#include<stdio.h>
#include<string.h>
int main()
{
int a,i;
printf("Enter the number of names you want: ");
scanf("%d",&a);
//Flush the input buffer
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
char names[50][50];
for(i=0;i<a;i++)
{
printf("%d name: ",i);
fgets(names[i],50,stdin); //Use fgets instead of gets
// To remove th \n registed by the fgets
char *p;
if ((p = strchr(names[i], '\n')) != NULL)
*p = '\0';
}
printf("The required name lists: \n");
for(int i=0;i<a;i++)
{
printf("%d name: ",i+1);
puts(names[i]);
}
return 0;
}
Reference:
Remove newline skipped by scanf
Remove newline registered by fgets
Put this after line scanf("%d",&a), as a workaround,
char c;
scanf("%c",&c);
Also use fgets(names[i],50,stdin) instead of gets(names[i])
Note: You get warning when you use gets in your code, as it is always assumes a consistent input from user. More explanation over here
Why is the gets function so dangerous that it should not be used?

Using character for sentinel but receiving pointer error

I'm trying to program a loop that counts characters until it receives a certain sentinel value. The sentinel value is supposed to be a #, but I've also tried a 0 and a Z and had the same response.
When it compiles, I receive "warning: comparison between pointer and integer" for lines 16 (the line that calls the sentinel.)
If I don't define the sentinel, but instead rely on logical operators in the while statement, then I receive no error, but have an endless loop.
Thanks!
#include <stdio.h>
int main()
{
#define SENTINEL '#'
char ch;
int chcount;
printf("Enter your text, terminate with a #:");
scanf("%s", &ch);
chcount = 0;
while (ch != SENTINEL)
{
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount +1;
printf("You have entered %d characters", chcount);
}
}
return(0)
}
With the %s format specifier, scanf expects the address of a char buffer, where the string you type will be copied.
And you gave the address &ch of a single char, which is obviously not enough to contain a "word" from input with its terminating null character.
Moreover, your loop reads no input from the user. Thus the endless loop.
This is because the way you use scanf(), with %s format specifier you are writing to a char*, not the char ch (as you've declared). In order to write to a single char variable, you should use a %c format specifier.
To fix this you should either use f.e. getchar() instead of scanf() or use scanf() (and change ch to char* then) but iterate over scanned string to check whether there is #.
I would recommend the first solution.
The while loop never ends so I changed your while loop.
I tried to change your program to:
#include <stdio.h>
#define SENTINEL '#'
int main()
{
char ch;
int chcount;
printf("Enter your text, terminate with a #:");
chcount = 0;
while ((ch = getchar()) != SENTINEL)
{
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount + 1;
printf("You have entered %d characters\n", chcount);
}
}
return(0);
}
Some issues I found with your code:
scanf("%s", &ch);
It should be
scanf("%c", &ch);
Next, semicolon missing here: return(0);
However, since your aim is:
I'm trying to program a loop that counts characters until it receives a certain sentinel value. The sentinel value is supposed to be a #
I suggest moving your scanf() inside while loop:
#include <stdio.h>
int main()
{
#define SENTINEL '#'
char ch='0';
int chcount;
printf("Enter your text, terminate with a #:");
chcount = 0;
int i=0;
while (ch != SENTINEL)
{ scanf("%c", &ch);
if ((ch >= 'A') && (ch <= 'Z'))
{
chcount = chcount +1;
printf("You have entered %d characters", chcount);
i++;
}
}
return(0);
}
here is a working version of the posted code.
It contains numerous corrections.
Corrections include consistent/usable indentation and logic corrections
Note: not all implementations have the getline() function
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int sentinelFound = 0;
#define SENTINEL '#'
char* line = NULL;
size_t lineLen = 0;
printf("Enter your text, terminate with a #:");
int chcount;
getline(&line, &lineLen, stdin );
size_t i;
for( i=0; i<lineLen; i++)
{
if( SENTINEL == line[i] )
{
sentinelFound = 1;
break;
}
if ((line[i] >= 'A') && (line[i] <= 'Z')) // only count capital letters
{
chcount = chcount +1;
}
}
free( line );
if( !sentinelFound )
printf( "You did not enter the sentinel character!" );
else
printf("You have entered %d capital characters\n", chcount);
return(0);
} // end function: main

C programming getchar()

I have two problems writing my code. The first problem I have is getting my getchar() to work if the user enters no text and just hits enter. I need to print an error if they do so and prompt the user to reenter the text in a loop until they do enter text. Is there any way to do so because everything I have tried has failed.
Here is the code I have for that section:
printf("Enter a text message: ");
while((c=getchar()) != '\n' && c != EOF)
{
text[i]= c;
i++;
}
I am new to C so I am limited on ideas to fix my dilemma. As you can see I am setting the input equal to an array. This leads to my second problem, I need to limit the input to no more than 100 characters. But, instead of giving the user an error I need to just chop off the extra characters and just read the first 100.
The simplest solution to your problem is to use fgets. We can give limit to the input so that it doesn't read the extra characters after the given limit.
Refer this sample code. Here I am printing the string if the user is not pressing Enter key:
#include <stdio.h>
int main()
{
char str[100];
fgets(str, 100, stdin);
if(str[0] != '\n')
{
puts(str);
}
return 0;
}
#include <stdio.h>
#define MAXSIZE 100
int main() {
char text[MAXSIZE+1]; // one extra for terminating null character
int i = 0;
int c;
while (1) {
printf("Enter a text message: ");
i = 0;
while ((c = getchar()) != '\n' && c != '\r' && c != EOF) {
if (i < MAXSIZE) {
text[i]= c;
i++;
}
}
if (i > 0 || c == EOF)
break;
printf("Empty string not allowed.\n");
}
text[i] = '\0';
printf("You entered: %s\n", text);
return 0;
}
Test code to detect non-compliant system:
#include <stdio.h>
int main() {
int c;
printf("Just hit enter: ");
c = getchar();
if (c == '\r')
printf("\\r detected!!!\n");
else if (c == '\n')
printf("\\n detected.\n");
else
printf("Yikes!!!\n");
return 0;
}
First of all getchar() can take only one character an input. It cannot take more than one character.
char c;
int total_characters_entered = 0;
do
{
printf ("Enter a text message: ");
c = getchar();
if (c != '\n')
{
total_characters_entered++;
}
} while (total_characters_entered <= 100);
I have written some code that will iterate in while loop until user has entered 100 characters excluding "Simple Enter without any text"
Please let me know if it does not satisfy your requirement. We will work on that.

String input with getchar

I've a little problem with my code, why when I use printf on string1 (last line), it doesn't give me what I wrote for this variable ?
For example if I wrote : asdfgh, string1 give me something weird like : #>>..
Any idea ?
Thanks for help.
int main()
{
int length;
int i = 0;
char string1[100];
printf("Please enter the length of the two strings\n");
scanf("%d", &length);
printf("\nPlease enter the first string\n");
while((string1[i] = getchar())!='\n')
i++ ;
getchar();
printf("\nString 1 : %c", string1);
return 0;
}
You have few problems there:
1) Should use %s for printing string.
2) Terminate the string with NULL terminator (It's not a string until then ;)
3) use a standard prototype for main(), such as: int main(void)
#include <stdio.h>
int main(void)
{
int length;
int i = 0;
int ch;
char string1[100];
printf("Please enter the length of the two strings\n");
scanf("%d", &length);
getchar();
printf("\nPlease enter the first string\n");
/* use null for termination of string */
/* Press Ctrl+d to end your input */
while((ch = getchar()) != EOF){
string1[i++] = ch;
}
string1[i] = '\0';
/* USE %s to print whole string */
printf("\nString 1 : %s\n", string1);
return 0;
}
Hope this will solve your problem

Resources