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.
Related
I'm trying to write a program in C that copies its input to its output while replacing each string of one or more Spaces with a single Space.
My code isn't doing that but is instead taking away every second character.
This is my code:
#include <stdio.h>
main()
{
int c;
int lastc;
lastc = 0;
while(getchar() != EOF){
c = getchar();
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
}
Your loop should look like:
while((c = getchar()) != EOF){
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
In your version you get a char with getchar while checking the condition for the while loop and then as a next step you again get a char with getchar. So the first one is not used in your code. Therefore it is taking away every second character.
Keep running in while loop until you get non-space character and print just one space after you get out.
int main()
{
int c;
bool space=false;
while ((c=getchar()) != EOF) {
while (isspace(c)) {
space = true;
c = getchar();
}
if (space) {
putchar(' ');
space = false;
}
putchar(c);
}
return 0;
}
I use fgets() function to getting string from input i.e stdin and store in the scroll string.
Then you must implement a way to analyze string to find spaces in it.
When you find first space, increase index if you face another space.
This is the code.
Code
#include <stdio.h>
int main(void){
char scroll[100];// = "kang c heng junga";
fgets(scroll, 100, stdin);
printf ("Full name: %s\n", scroll);
int flag = 0;
int i=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
printf("%c",scroll[i]);
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
return 0;
}
Sample input: Salam be shoma doostane aziz
Program output: Salam be shoma doostane aziz
[Edit]
Use new string st to hold space eliminated string an print as output.
Also this code work for Persian string.
char scroll[100]={0};// = "kang c heng junga";
printf("Enter a string: ");
fgets(scroll, 100, stdin);
printf ("Original string: %s\n", scroll);
char st[100]={0};
int flag = 0;
int i=0;
int j=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
st[j]=scroll[i];
j++;
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
printf("Eliminate Spaces: %s", st);
Write a program that reads lines from the standard input. Each line is printed on the standard output preceded by its line number. Try to write the program so that it has no built in limit on how long a line it can handle.
#include <stdio.h>
int main()
{
int ch;
int pos = 1;
printf("Enter the line :\n");
while ((ch = getchar()) != EOF)
{
if (pos == 1)
{
printf("%d\t", pos);
pos++;
}
putchar(ch);
if (ch == '\n')
printf("%d\t", pos++);
}
}
OP's code is almost there.
Keep track of line number and column position.
User input might not end with a '\n'. Better to increment and print the line number when in column position 0 and data has arrived.
To avoid numeric limits, code could use a wider type than int.
#include <stdio.h>
int main(void) {
int ch;
long long line_count = 0;
long long column_position = 0;
printf("Enter the line :\n");
while ((ch = getchar()) != EOF) {
if (column_position == 0) {
printf("%lld\t", ++line_count);
}
column_position++;
putchar(ch);
if (ch == '\n') {
column_position = 0;
}
}
fflush(stdout); // insure any last line without a \n is printed before quitting
}
Is very easy (and faster) using fgets.
Just print the line, then search for a trailing newline (strchr can help) and if you find it, print the number of line.
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[2048];
int ln = 0;
printf("%5d) ", ++ln);
while (fgets(str, sizeof str, stdin)) {
printf("%s", str);
if (strchr(str, '\n')) {
printf("%5d) ", ++ln);
}
}
puts("EOF");
return 0;
}
I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
my code is:
char GetStuff(void)
{
char c;
scanf("%c", &c);
while(c != 'A' || c != 'P')
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:
putting a white space before/after %c like:
scanf(" %c", &c);
write a separate method or include in this GetStuff method to clean the newline like:
void cleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
Can anyone help me with this problem please? Thank you in advance.
Please consider the following snippet:
#include <stdio.h>
#include <ctype.h>
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf ("%c", &c);
// clean input buffer (till the end of line)
while(getchar()!='\n');
} while(toupper(c) != 'A' && toupper(c) != 'P');
return c;
}
int main(void)
{
printf("Your input is'%c'\n", GetStuff());
return 0;
}
Note the points:
condition while(c != 'A' || c != 'P') will be always true (just because one character cannot be 'A' and 'P' at the same time), so use while(c != 'A' && c != 'P') instead
No need for two scanf if you use do..while loop
After entering a char with scanf it is recommended to clean all characters from buffer, e.g. with while(getchar()!='\n'); (this will clean all input including incorrect and redundant characters)
use toupper to avoid making 4 comparison (actually single c=toupper(c) inside loop can minimize your while as while(c != 'A' && c != 'P') )
UPDATE:
To add message "Invalid input" and adding some other useful improvement subjected befor... new code is as:
#include <stdio.h>
#include <ctype.h>
void CleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
char GetStuff(void)
{
char c;
do {
printf("Please enter A for AM or P for PM: ");
scanf (" %c", &c);
c = toupper(c); // here letter become uppercase
CleanBuffer();
} while( (c != 'A' && c != 'P')?printf("Invalid input! "):0 );
return c;
}
int main(void)
{
printf("You have entered: %c\n", GetStuff());
return 0;
}
Note: function will return 'A' or 'P' in uppercase, so if this is not needed change the code as in example before update (use two toupper and do not change c after scanf). Also you can use tolower as an option (of course with comparing to 'a' and 'p').
#include <stdio.h>
char GetStuff(void) {
char c;
scanf("%c", &c);
getchar();
while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &c);
getchar();
}
return c;
}
int main(void) {
printf("Calling GetStuff()...\n");
char x = GetStuff();
printf("User entered %c\n", x);
return 0;
}
You are using while (c != 'A' || c != 'P') as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.
Also, call getchar() after your scanf statements, to capture the newline. This should work the way you want it to.
Inside loop you are taking input in dtChar but your loop condition checks variable c which is not updated in the loop, that is causing infinite loop
Also you would change your condition
while(c != 'A' || c != 'P')
to
while(c != 'A' && c != 'P')
If you want user to enter either 'A' or 'P'
Another possible solution. As others mentioned the condition was to be done with &&. Anyway the big problem is how to remove what's left on the console input line. Since the console works by lines, we remove everything up to the next '\n'. If the user already left something on the input line before calling GetStuff(), it would be useful to add a call to SkipRestOfTheLine() before the while loop.
In general I suggest to start with a while(1) loop, before making it nicer (such as in the cleanBuffer() you posted).
#include <stdlib.h>
#include <stdio.h>
void SkipRestOfTheLine(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF || c == '\n')
break;
}
}
char GetStuff(void)
{
while (1) {
int c = fgetc(stdin);
if (c == EOF)
exit(EXIT_FAILURE); // Deal with this case in an appropriate way
if (c == 'A' || c == 'P')
return c;
printf("invalid input, enter again (A for AM or P for PM): ");
SkipRestOfTheLine();
}
}
int main(void)
{
char c = GetStuff();
return 0;
}
try this,
char GetStuff(void)
{
char c;
scanf("%c", &c);
while (((c != 'A') || (c != 'a')) && ((c != 'P') || (c != 'p'))==1)
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
I hope this works, some time because of not given proper bracket it is stuck in the loop.
#include <stdio.h>
int main(){
char c;
do{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%s", &c);
}while ((c != 'A') && (c != 'P'));
return 0;
}
I have just started learning C, been reading a C textbook by Keringhan and Ritchie. There was this example in the textbook, counting characters from user input. Here's the code:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF) {
if (getchar() != 'q')
++nc;
else
break;
}
printf("%ld\n", nc);
}
The problem is, when I execute the code, if I input only one character per line, when I input "q" to break, it doesn't do so. I have to type some word per line, only after that it will break the loop. Also, it only counts the half of the characters of the word. I.e. if I input
a
b
russia
it will only print '5' as final result.
Could you please explain to me why is this happening?
This works, but only when you finish off with an Enter. So, this will count the characters until the first "q" appears. That is just how getchar() and getc(stdin) work.
#include <stdio.h>
int main() {
char c = 0;
long count = 0;
short int count_linebreak = 1; // or 0
while((c = getchar()) != EOF) {
if(c != 'q' && (count_linebreak || (!count_linebreak && c != '\n'))) {
++count;
}else if(c == 'q') {
printf("Quit\n");
break;
}
}
printf("Count: %ld\n",count);
return 0;
}
A StackOverflow question about reading stdin before enter
C read stdin buffer before it is submit
Im writing a simple program to count the number of character user is entered, and i wrote an if to check wether there is a newline but still printing it..
the code:
#include <stdio.h>
int main()
{
char ch;
int numberOfCharacters = 0;
printf("please enter a word, and ctrl + d to see the resault\n");
while ((ch = getchar()) != EOF)
{
if (numberOfCharacters != '\n')
{
numberOfCharacters++;
}
}
printf("The number of characters is %d", numberOfCharacters);
return 0;
}
what am i doing wrong?
Think about this line:
if (numberOfCharacters != '\n')
how can it make sense? You are comparing the number of characters read so far with a newline, it's like comparing apples to oranges and surely won't work. It's another variable that you should check...
Change your loop to this.
while ((ch = getchar()) != EOF)
{
if(ch != '\n')
numberOfCharacters++;
}