String input with getchar - c

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

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?

get and check Strings in c language

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.

Converting string value to int equivalent in C

Can someone tell me what's wrong with this:
int main()
{
char a[100];
int i = 0;
printf("Enter a number: ");
scanf("%c", &a[i]);
printf("The number you've entered is: %d", a[i] - '0');
}
Brief summary: I am trying to convert a number stored in a char array to its int equivalent. I know in C#, you use the intparse command, but because there isn't such one in C, I do not know what to do. When I input a two digit number, it is only outputting the first digit, of the input char.
strtol sample
#include <stdio.h>
#include <stdlib.h>
int main(){
char str[16], *endp;
int value;
printf("Enter a number: ");
fgets(str, sizeof(str), stdin);
value = strtol(str, &endp, 0);
if(*endp == '\n' || *endp == '\0'){
printf("The number you've entered is: %d\n", value);
} else {
printf("invalid number format!");
}
return 0;
}
If you mean to print ASCII value of char the no need to do a[i] - '0'.
Try this
printf("The number you've entered is: %d", a[i]);
If you are talking about string then first change your scanf statement to
scanf("%s", a);
or better to use fgets library function instead of scanf;
fgets(a, sizeof(a), stdin);
and then use strtol function.
OP method of scanf("%c", &a[i]); only handles a 1 character input.
To read the entire line, suggest using fgets() to read.
The convert to a long using strtol().
Watch for potential errors.
#include <stdio.h>
#include <stdlib.h>
int main(){
// use long to match strtol()
long i;
// size buffer to handle any legitimate input
char a[sizeof i * 3 + 3];
char *endptr;
printf("Enter a number: ");
if (fgets(a, sizeof a, stdin) == NULL) {
// If you would like to handle uncommon events ...
puts("EOForIOError");
return 1;
}
errno = 0;
i = strtol(str, &endptr, 10);
if(*endptr != '\n' /* text after number */ ||
endp == a /* no text */ ||
errno /* overflow */) {
printf("Invalid number %s", a);
}
else {
printf("The number you've entered is: %ld\n", i);
}
return 0;
}
Try
char myarray[5] = {'-', '4', '9', '3', '\0'};
int i;
sscanf(myarray, "%d", &i); // i will be -493
Edit (borrowed from [1]):
There is a wonderful question here on the site that explains and compares 3 different ways to do it - atoi, sscanf and strtol. Also, there is a nice more-detailed insight into sscanf (actually, the whole family of *scanf functions).
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a[100];
int final=0,integer;
int i;
printf("Enter a number: ");
gets(a);
for(i=0;a[i]>='0'&&a[i]<='9';++i)
{
integer=a[i] - '0';
final=final*10+integer;
}
enter code here
printf("The integer is %d ", final);
}

I want to find the ascii value of this string and the average number of character

I have done up to this
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter any string: ");
scanf("%s",str);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
return 0;
}
I don't get all the ASCII values when I tried to compile it. Will you please tell me where is my mistake.
It stops where it encounters where you give space in input.
So if you entered
Hello World scanf will display ascii values of characters in Hello only.
Solution: use fgets
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter any string: ");
fgets(str, sizeof(str), stdin);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
return 0;
}
First; indent your code correctly (on Linux you could use the GNU indent utility, or astyle).
Compile it with all warnings and debugging info (e.g. gcc -Wall -g). Learn how to use the debugger (gdb) to run it step by step.
Then, your scanf("%s", str); is dangerous (should at least be scanf("%99s", str);, see scanf(3)) ! You could get crashes or undefined behavior if the user enters a very long "word" of 200 characters (e.g. 200 times the digit 0). Alos notice that %s reads up to a space or blank-like character. I believe it is good habit to zero a buffer before reading it. So replace your scanf with
memset (str, 0, sizeof(str));
fgets (str, sizeof(str), stdin);
At last, you are not flushing the buffered stdout output (see stdio(3), setvbuf(3), fflush(3), etc...). Try perhaps
while(str[i])
printf("%d ",str[i++]);
putchar('\n');
fflush(stdout);
The last call to fflush is useless here, but it is a good habit (or else end every printf format string with a newline \n since stdout is often but not always line-buffered!)
scanf stops reading if there is a space in the input string. You can either uses fgets or do the follwing:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter any string: ");
str[i] = getchar();
while(str[i]!='\n'){
str[i+1] = getchar();
i++;
}
str[i] = '\0';
printf("%s\n",str);
i=0;
printf("ASCII values of each characters of given string: ");
while(str[i]!='\0'){
printf("%d ",str[i++]);
}
return 0;
}
EDIT:
To find average of the string a asked by you in comments:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int sum=0;
int average=0;
int i=0;
printf("Enter any string: ");
str[i] = getchar();
while(str[i]!='\n'){
str[i+1] = getchar();
i++;
}
str[i] = '\0';
printf("%s\n",str);
i=0;
printf("ASCII values of each characters of given string: ");
while(str[i]!='\0'){
sum = sum + str[i];
printf("%d ",str[i++]);
}
// To calculate average
average = sum/(i-1);
printf("\nAverage = %d\n",average);
return 0;
}

Resources