scanf keeps running nonstop - c

I have been trying to run the scanf() on my mac, but it never worked (took forever to run the program). Everything else like the printf works fine!
#include <stdio.h>
#include <stdlib.h>
int main(){
char name[20];
printf("What is your name? \n");
scanf("%19s", name);
return 0;
}
terminal
[Running] cd "/Users/yiminghuang/Documents/C/" && gcc scanf4.c -o scanf4 && "/Users/yiminghuang/Documents/C/"scanf4
[Done] exited with code=null in 8.611 seconds
[Running] cd "/Users/yiminghuang/Documents/C/" && gcc scanf4.c -o scanf4 && "/Users/yiminghuang/Documents/C/"scanf4
[Done] exited with code=null in 10.384 seconds
[Running] cd "/Users/yiminghuang/Documents/C/" && gcc scanf3.c -o scanf3 && "/Users/yiminghuang/Documents/C/"scanf3
[Done] exited with code=null in 15.999 seconds

I am new to C programming, so please excuse me if I fail to answer your question correctly!
Now, the program you wrote works perfectly fine but as soon as you enter a string separated by a space, it only takes the characters before the space.
To solve this problem, you can use fgets() function of C.
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main(){
char name[MAX];
printf("What is your name? \n");
fgets(name, MAX, stdin);
printf("String = %s", name);
return 0;
}
//i have used fgets() here for getting the input
//it is a better option than gets()
//since it bounds your array and prevents buffer overflow
I have also added a printf() to check if the string is stored correctly.
IMPORTANT: fgets() also consider the newline character i.e. '\n' as a part of your string. So better to keep that in mind.
Check this question to know more about fgets()
Regards!

Related

scanf() function failure

I installed the MingW C compiler and I am trying to compile and run a C program there.
I use Visual Stdio Code IDE.
OS is WINDOWS 10.
Compiler is MinGW.
My programs that do not use scanf() or gets() all run successfully but when I use scanf() function the program does not take input. I also used gets() function but that has the same problem. So when I press "run" button it does not give any output.
Here is my minimal reproducible example. Is this a compiler problem or is my code wrong?
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
//scanf("%d", &n);
}
OUTPUT for the above code is:
[Running] cd "d:\code\C\" && gcc #13sum.c -o #13sum && "d:\code\C\"#13sum
Enter a number:
[Done] exited with code=0 in 0.29 seconds
If I add a scanf():
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
}
OUTPUT for the above code is:
[Running] cd "d:\code\C\" && gcc #13sum.c -o #13sum && "d:\code\C\"#13sum
[Done] exited with code=1 in 31.526 seconds
After using fflush(stdout);
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
fflush(stdout);
scanf("%d", &n);
}
[Running] cd "d:\code\C\" && gcc #13sum.c -o #13sum && "d:\code\C\"#13sum
Enter a number:
[Done] exited with code=1 in 2.804 seconds
After using fflush(stdout); printf() statement is executed but now I am unable to enter the value. I am typing but it is not showing in the output .
Compiler is not any giving errors in any of the above case.
the problem is your compiler its working fine for me.
your code take input until you enter 0 and then print the sum.
here's my output:-
Enter a number: 45 Enter a number: 34 Enter a number: 0 Sum is = 79%
so, check if you installed your mingw C compiler properly here.

Avoid pressing enter with getch() on Linux ( GCC ) "No-echo"

In the next code: I don't have to press Enter to get the character with getch() and this is only applicable on Windows (mingw) . I am programming a simple stopwatch which reacts if a keyboard-key is pressed without the need to press ENTER, but the same thing doesn't work on Linux ( GCC ). And I have to find a solution only using getch() with no echo. I've been Googling around with no luck. Thank you in advance.
PS: I am a c/c++ beginner.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
printf("\n\t\tStopwatch \n\n \t Press S to start \n\n");
time_t start;
char c ;
struct tm tm ;
do {
c=getch(); /*get the Character without pressing ENTER*/
if (c!= 'S' && c!= 's') printf("\nWrong key. Please press'S' to Start\n");
} while(c!= 'S' && c!= 's');
start=time(NULL);
tm = *localtime(&start);
printf("\n Starting time :: %d:%d:%d \n", tm.tm_hour, tm.tm_min, tm.tm_sec);
return 0;
}
Unix (and so Linux) have a concept of terminal (TTY) which can be pretty complicated.
Every process can be associated with a terminal (and lot actually are).
This terminal has different options like the ECHO you mentioned and the LINE BUFFER (which is the enter problem which you reported).
To set a terminal the low level APIs are termios (see "man termios").
Another more friendly API is ncurses (see "man ncurses"). For instance at https://www.mkssoftware.com/docs/man3/curs_inopts.3.asp you can see some function for different settings.
An easy example with ncurses (you can compile with "gcc -O2 source.c -o output -lncurses"):
#include <stdio.h>
#include <ncurses.h>
int main(void)
{
initscr();
cbreak();
noecho();
int n = getch();
printf("%d %c\n", n, n);
}

Cannot run program

I started learning C programming with C Programming Language by Denis M Ritchie I am trying to execute program from that book
#include <stdio.h>
/* count lines in input */
main()
{
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
getchar();
}
However all I get is blank console and when I type text and press enter,no value is displayed.
I am using Visual Studio 2013 IDE.
The program you posted here is for counting number of lines.
Q. However all I get is blank console and when I type text and press
enter,no value is displayed
A. Yes it shows nothing because while ((c = getchar()) != EOF) waits until you enter EOF (use ctrl + z then you will get number for lines).
getchar(c);
See declaration of getchar.
int getchar(void)
It doesn't take any parameter. Didn't it gave you error.
And main should be int main.
There are several issues. First, main has to have a type, usually int
- main()
+ int main()
and your program should return an exit status
Secondly getchar takes no arguments, and returns the input
http://www.tutorialspoint.com/c_standard_library/c_function_getchar.htm
- getchar(c)
+ c = getchar()
You can compile your program by calling
gcc -Wall test.c -o test
Where test.c is your code, and test is the binary. -Wall will show all the "warning" (errors that don't interfere with the program execution)
I believe that you use Windows, it's better to add:
system("pause");
Moreover to use system("pause"), only in Windows, you need to include another library:
#include <stdlib.h>
You can see your results but the problem here, is that you have an infinite loop. Yo need to check the \n, count and when you have a specific number, you leave from the loop.

No compiler errors, but there is a bug somewhere

I compiled with "gcc -ansi -pedantic -W -Wall -o ". I only get 2 errors when I compile, and here they are:
easter_eggs.c: In function ‘main’:
easter_eggs.c:23:18: warning: multi-character character constant [-Wmultichar]
if (prompt == 'egg1')
^
easter_eggs.c:23:4: warning: comparison is always false due to limited range of data type [-Wtype-limits]
if (prompt == 'egg1')
when I run the program and hit S, it displays the top 2 printf statements 2 times each. If I type anything and press enter nothing happens it just goes back to the prompt. Even if I type egg1, it still goes back to prompt. Here is the source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char first_option;
char prompt[16];
system("clear");
system("toilet -f future -F gay Easter Eggs");
printf("\nFind all the easter eggs and you win. Simple enough.\n");
printf("Hit S to start and Q to quit\n");
scanf("%c", &first_option);
if (first_option == 's')
{
while (1)
{
printf("To exit hit Ctrl + C\n");
printf("You must find all easter eggs simply by typing stuff in the prompt below: \n");
memset(prompt, 0, sizeof(prompt));
scanf("%16s", prompt);
getchar();
if (!strcmp(prompt, "egg1"))
{
printf("Found 1\n");
}
}
}
if (first_option == "q")
{
exit(0);
}
else
{
printf("Invalid input. Press Enter to continue\n");
getchar();
main();
}
return 0;
}
Edit 1: I have edited the source
Edit 2: Changed the source again. This time I use strcmp() to compare the strings, not ==
Last Edit: I managed to make it work. Also updated the source so that it works. Thx to all for being patient with me. Havn't slept in idk how many days. :/
Read more about C programming. You are confused about char and strings.
If you want to read a word as a a string of at most 16 bytes with a terminating null byte, use e.g.
char prompt[16];
memset (prompt, 0, sizeof(prompt));
if (scanf("%15s", prompt)<1) return;
if (!strcmp(prompt, "egg1")) {
/// found
Also, you are right to compile with -Wall. But compile also with debugging information and extra warnings:
gcc -Wall -Wextra -g easter_eggs.c -o easter_eggs
and learn how to use the gdb debugger.
Read also the man pages (type man man in your Linux terminal) of scanf(3) & strcmp(3)
When you compare a char variable, you have to compare it with a char.
As the compiler told you, you have a multi-character here.
strcmp() will help you.
As mentioned in other comments, Read C. Below are some suggestions
To store string in C, You must use char[] or char * after allocating memory.
You cannot use == operator to compare strings. Use strcmp() instead.

Beginner C programmer having problems with string functions

I'm a C noob, going back to school for my masters in CS so I'm taking some time to ramp up my skills. I wanted to see if anybody could lend some assistance on why I'm having problems compiling the following code. I've been following the videos on WiBit.net and develop on a 64 bit Linux environment (Ubuntu 13.10). I am using gedit and the gcc compiler no IDE.
This code runs on my Win 7 VM without errors, however when I try to execute it on my host Linux environment I'm getting errors:
Source Code: This example calls the strcmp and strcmpi functions
#include <stdio.h>
#include <string.h>
int main()
{
char str1[255];
char str2[255];
printf("str1: "); gets(str1);
printf("str2: "); gets(str2);
if(strcmp(str1, str2) == 0)
printf("Strings match exactly!");
else if(strcmpi(str1, str2) == 0)
printf("Strings match when ignoring case!");
return 0;
}
Error Message (Linux ONLY):
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
/tmp/ccwqdQMN.o: In function main':
main.c:(.text+0x25): warning: thegets' function is dangerous and should not be used.
main.c:(.text+0x8f): undefined reference to `strcmpi'
collect2: error: ld returned 1 exit status
Source Code 2: This example uses the strupr and strlwr functions
#include <stdio.h>
#include <string.h>
int main()
{
char str1[255];
char str2[255];
printf("str1: "); gets(str1);
printf("str2: "); gets(str2);
strlwr(str1);
strupr(str2);
puts (str1);
puts (str2);
return 0;
}
Error Message (Linux ONLY):
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1
/tmp/ccWnIfnz.o: In function main':
main.c:(.text+0x25): warning: thegets' function is dangerous and should not be used.
main.c:(.text+0x57): undefined reference to strlwr'
main.c:(.text+0x6b): undefined reference tostrupr'
collect2: error: ld returned 1 exit status
I would love a detailed explanation if someone is willing to help and not tear me apart haha. I know that for best practices we shouldn't use gets due to buffer overflow (for example the user enters a 750 character string). Best practices would use fgets instead but my question is whether I'm getting these errors because these functions aren't part of ANSI C or what. They do show up in the man files on my machine which is throwing me through a loop.
Thanks in advance!
UPDATE:
You guys are awesome. Took all of your advice and comments and was able to revise and make a sample program for string comparison as well as conversion to upper/lower. Glad I was able to get it running on both OSes error free as well.
Sample code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char str[255];
printf("Enter a string: "); fgets(str,255, stdin);
printf("Here is your original string, my master: %s\n", str);
//Now let's loop through and convert this to all lowercase
int i;
for(i = 0; str[i]; i++)
{
str[i] = tolower(str[i]);
}
printf("Here is a lowercase version of your string, my master: %s\n", str);
//Now we'll loop through and convert the string to uppercase
int j;
for(j = 0; str[j]; j++)
{
str[j] = toupper(str[j]);
}
printf("Here is a uppercase version of your string, my master: %s\n", str);
return 0;
}
strcmpi problem: strcasecmp() is the posix standard and so is it in linux.
strupr and strlwr doesn't exist in glibc, although you can implement them with a single line of code, as this:
c - convert a mixed-case string to all lower case
In the compilation, first you can find a warning, because the gcc doesn't find the functions in the included header. In such cases it thinks they are declared as int funcname(void). But later, while linking, it can't find the exported symbols of this nonexistant functions, and thus it can't create the executable. This second error is what stops the compilation.
There are too many difference in the c apis, although the posix standard handles them, microsoft don't follow it.
As you noted, the gets function is unsafe because it does not perform any boundary checking: you have called it with a 255-character string buffer, but if another program wrote a line longer than 255 characters, it could write data into your process's stack, and thereby cause your process to execute malicious code (or at the very least produce a segmentation fault).
Use fgets instead:
printf("str1: "); fgets(str1, 255, stdin);
printf("str2: "); fgets(str2, 255, stdin);
If you read the error output from the compiler carefully, you'll note that it's not issuing an error on your use of gets but a warning. Your code should still compile and execute if you fix the strcmpi call.

Resources