How do I use getchar() like scanf()? - c

I was shown this program to read an entire string:
#include <stdio.h>
int main(int argc, char *argv[]){
int something;
printf("Enter something \n");
while (scanf("%c", &something)==1) {
printf("%c", something);
}
return 0;
}
When I enter hello world it outputs hello world.
Can someone please explain why it doesn't output:
h
e
l
l
...
because I thought loops go over one letter at a time I'm confused as to why it didn't output like that. Now, I tried to write a program that does the same thing using getchar instead:
#include <stdio.h>
int main()
{
char c;
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
return(0);
}
When I enter hello world this program just outputs h. How can I use getchar to do the same thing as the first program? Also, what are the differences between getchar and scanf?

getchar() takes one character input at a time. If you want it to read a whole string or a character array, you may use a while loop or a for loop to store each character one by one. Eg : c[i]=getchar() for i = 0 to string length, or while c[i]!='\n'

In the first program, the problem is the line
printf("%c", something);
It's missing a newline character, it should be
printf("%c\n", something);
if you want to print one character per line.
The problem with the second one is that you are reading only one character with getchar() function. You can't read in the whole string on the same line with getchar(), you can try gets(char* s) instead. And you need to loop over putc() to dump all the characters.

Related

I wrote a program using ENTER to stop the program but it isn't working

I wrote this program to read a small amount of Spanish and English words from a file and prompt for an English word and get the Spanish translation. To stop the program they must press enter only. The program doesn't stop however, it just keeps waiting for another word. This is the program
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE*in=fopen("input.txt","r");
char English[9][20],Spanish[9][20],word[20];
int find(char[],char[][20]);
for(int j=0; j<=8;j++)
fscanf(in,"%s",English[j]);
for(int r=0;r<=8;r++)
fscanf(in,"%s",Spanish[r]);
printf("type some English word to stop press enter only\n");
scanf("%s",word);
while(strcmp(word,"")!=0){
int t=find(word,English);
printf("the Spanish word for %s is %s\n",word,Spanish[t]);
printf("type some english word to stop press enter only\n");
scanf("%s",word);}
fclose(in);
}
int find(char word[],char English[][20]){
for(int j=0;j<=8;j++)
if(strcmp(English[j],word)==0) return j;
}
I thought pressing ENTER would save the empty string "" in the array word and the program would stop. This is the code for that.
while(strcmp(word,"")!=0)
I'm really new to coding, I don't know why it isn't working.
You can do it like this, just make the character q for quit:
while(strcmp(word,"q")!=0){
int t=find(word,English);
printf("the Spanish word for %s is %s\n",word,Spanish[t]);
printf("type some english word to stop press enter only\n");
scanf("%s",word);
}
printf("\nExiting...\n");
"New to coding" and "confused by scanf" is a universal truth. Seriously, do not use scanf at all until you understand the language well enough to realize that you do not really ever need it. That said, you can do:
$ cat a.c
#include <stdio.h>
int
main(void)
{
char word[1024];
char c;
int rc;
while( ( rc = scanf("%1023[^\n]%c", word, &c)) == 2 ) {
printf("word = %s\n", word);
}
return 0;
}
$ printf 'foo\nbar\n\nignored\n' | ./a.out
word = foo
word = bar
The format string matches everything up to a newline and stores it in word, and then consumes the newline with %c. (You could also use %*c and not provide a variable to be assigned.) When there are two adjacent newlines in the input stream, the first conversion specifier fails to match the second newline and the loop terminates. Note that this will fail if any line of input exceeds 1023 chars. Two general rules here: 1) %s cares about whitespace, and if you want to handle whitespace specially you should use %[ insteead of %s, and 2) always, always, always check the value returned by scanf. If you ever call scanf and it is not in an if condition or a loop control or the right hand side of an assignment, it is an error.

Print a middle character of a string

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;
}

Trying to create a guess my letter code. How do I incorporate the case where the input char from the user equals my letter?

I am trying to create a program that compares the letter a user inputs to my letter. If the letters are the same, the program should say that they are the same, then terminate. If they are not the same, then the user should be prompted to enter another character until they guess it correctly.
I have tried nesting an if statement and nesting a while loop to achieve the case where the letters are equal.
#include <stdio.h>
int main()
{
char myLetter = 'a';
printf("insert a char:");
char userLetter;
scanf("%1s", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf("%1s", &userLetter);
}
while (userLetter == myLetter)
{
printf("char matches! program will terminate now. ");
break;
}
}
expected:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
char matches! program will terminate now.
actual:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
a does not match mine, try again:a does not match mine, try again:^C
The proper format operator for reading a single character is %c, not %1s. The latter reads a single character, but writes it into a null-terminated string, so it will write a null byte outside the userLetter variable, which causes undefined behavior.
You should put a space before the operator to make scanf skip over whitespace before reading the character. This is needed to make it ignore the newline after each response.
You should also turn off output buffering or flush the buffer after each prompt, since they don't end with a newline.
There's no need for the while loop at the end, since you don't get out of the first loop until the characters match.
This is a working version:
#include <stdio.h>
int main()
{
char myLetter = 'a';
setbuf(stdout, NULL);
printf("insert a char:");
char userLetter;
scanf(" %c", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf(" %c", &userLetter);
}
printf("char matches! program will terminate now.\n");
}
If you are comparing 2 char why don't you get user letter with scanf("%c", userLetter) and then you can compare them with = or != operator. If you are getting input expecting a string value, then I suggest you to declare userLetter like this:
char* userLetter[1];
and then use scanf the way you did in your code BUT you have to compare the strings with strcmp function.

How to capitalize the first letter of each word in an array in C

I am trying to make a simple program that stores a user-input sentence in an array of at most 80 characters and then capitalizes each word of in the sentence. I think I'm on the right track, however when I run the program, only the first word of the sentence is displayed.
#include<stdio.h>
int main(void)
{
int i; /*indexing integer*/
char sen[81]; /*specify total of 80 elements*/
printf("Enter a sentence no longer than 80 characters: \n\n");
scanf("%s",sen);
if((sen[0]>='a') && (sen[0]<='z'))
{
sen[0]=(char)(sen[0]-32); /*-32 in ascii to capitalize*/
}
for(i=0;sen[i]!='\0';i++) /*loop until null character*/
{
if(sen[i]==' ') /*if space: next letter in capitalized*/
{
if((sen[i+1]>='a') && (sen[i+1]<='z'))
sen[i+1]=(char)(sen[i+1]-32);
}
}
printf("%s",sen);
return 0;
}
I have a feeling it is only printing the first word in the array because of the first if statement after the scanf, but I am not completely sure. Any help would be appreciated. Thanks.
By default, the %s conversion specifier causes scanf to stop at the first whitespace character. Therefore you could either use the %80[^\n] format or the fgets function.
#include <stdio.h>
scanf("%80[^\n]", sen);
Or:
#include <stdio.h>
fgets(sen, sizeof sen, stdin);
However, since scanf reads formatted data, human inputs are not suitable for such readings. So fgets should be better here.
I have a feeling it is only printing the first word in the array because of the first if statement after the scanf
No, that's because the %s specifier makes scanf() scan up to the first whitespace. If you want to get an entire line of text, use fgets():
char sen[81];
fgets(sen, sizeof(sen), stdin);
dont use scanf when you want to take multiple words as input: use either gets() or fgets()..
I run your code with gets() and puts() and it worked.

C Prints One Char More Without Value

I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts to give the value.
#include <stdio.h>
int main() {
char ch;
int t;
while(t < 3){
scanf("%c\n", &ch);
printf("%c - %d\n", ch,ch);
t++;
}
}
http://i54.tinypic.com/2mdqb7d.png
Variable t is not automatically initialized to 0 by compiler. So You need to initialize t with 0. If printf doesn't print immediately it means the data is buffered. If you want to see immediatley you may consider flushing stdout right after printf.
I saw this several times, and don't know the root cause, but solution that works is:
scanf("\n%c", &ch);
It probably has something to do with buffered end of line character.

Resources