My command window crashes after i input a name. C - c

So that's my code, but every time I run it the command window crashes right after I input a name. I'm using Visual Basic, so it gives me a warning when I try to use:
scanf()
so instead i decided to use:
scanf_s
I also tried to change the %s in scanf_s("%s\n", name) to %c. It stopped crashing and executed the program but when it prints the name, it would just be a bunch of broken text.
#include <stdio.h>
int main(void) {
char name[30];
printf("Enter your name:\n");
scanf_s("%s\n", &name);
printf("%s\n", name);
}

Change the scanf line to
scanf("%29s", name);
Since your array has 30 positions, it shouldn't read more than 29. The last one is for the null terminating char

Related

How can i detect just the new line input using scanf, and printing directory, like terminal

I wanna reproduce the terminal behavior when the input is just a new line (keeps printing the same string), but don't know how to do it.
Example: When the user just inputs a new line, the terminal keeps printing the directory, until a real command is inserted
int main()
{
char userInput[1024];
while (1)
{
printf("directory »» ");
scanf("%[^\n]" , userInput); // This scanf doesn't work
while (userInput[0] == '\n') // If the input is only a new line char, keep asking for more inputs and printing the directory
{
printf("directory »» ");
scanf(" %[^\n ]" , userInput); // This scanf doesn't work
}
//Input isn't a NewLine, process the input
process_Input_Function(userInput); //Isn't empty, search for my created commands
}
}
At the first enter press, it enters the loop, reproduce 1 time, and then the scanf doesn't detect new lines anymore, it just skips and waits to a real string.
What can i type inside of the scanfto detect a new line input and keep printing that string till a real command is inserted?
I tried with scanf("%c"...) but the problem with a char, is that i can't process the whole string command, if isn't empty
First of all, your two scanf calls are different. The first one is
scanf("%[^\n]", userInput);
which looks for anything that's not a newline, as you wish to do.
But the second one is
scanf(" %[^\n ]", userInput);
which is also looking for a space before the input, followed by any character that is also not a newline or a space. Thus, scanf is waiting for the space.
IMHO, the best way to recreate this behavior is going to be in the parsing step, after you have gotten the command from the command line. Essentially, your command input loop would look like this:
char *userInput = NULL;
size_t n = 0;
while (true) {
// print the prompt
printf(">");
// get the line
ssize_t userInputLength = getline(&userInput, &n, &stdin);
// parse the input, using a function you wrote elsewhere
parse(userInputLength, userInput);
}
(Note the use of POSIX getline() instead of scanf. This is a more recent standard library function that does exactly the task of getting a line of user input, and also allocates the buffer using malloc and realloc so that you don't have to care about buffer overflows or even sizing the buffer at all.)
The user input function wouldn't care that the userInput portion was blank. The function that would care is the parse function, which will simply interpret a blank userInput string as "do nothing" and continue on its merry way.
Hmm, the code I gave pretty much does that with one exception, it doesn't display a prompt each time...
Is this what you mean:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // For the memset()
int main() {
char userInput[1024];
while (1) {
printf("»»» ");
fgets(userInput, 1024, stdin);
while (userInput[0] == '\n')
{
printf(">>> ");
memset(userInput, '\0', 1024);
fgets(userInput, 1024, stdin);
}
// Your command can be accessed from here //
printf("Command entered: %s\n", userInput);
printf("Input isn't a NewLine\n");
}
}
I changed the scanf() to fgets() to read from stdin so that we don't overwrite the buffer.

scanf is causing my code to run on forever

I was trying to use scanf but when I run the code the code goes on forever. And when I stop the code I get
[Done] exited with code=1 in 28.291 second
My question is what am I doing wrong? Here is the code I was trying to execute. My editor is VS code 1.21.0.
#include <stdio.h>
#include <string.h>
int main(){
char midInitial;
printf("What is your middle initial? ");
scanf(" %c", &midInitial);
printf("Middle inital &c ", midInitial);
}
The code does not run forever, it is waiting for the user to complete the input. Standard input is line buffered, so the user must type enter after the character for scanf() to process it. It will skip any white space characters, store the first non white space character into midInitial and return 1.
Another possible explanation is the environment you use does not support console input. Run your program from shell interpreter window in Windows.
There is another problem: the format "Middle inital &c " is incorrect, use % for conversion specifiers.
Here is a corrected version:
#include <stdio.h>
int main() {
char midInitial;
printf("What is your middle initial? ");
if (scanf(" %c", &midInitial) == 1) {
printf("Middle initial: %c\n", midInitial);
}
return 0;
}
go to code-runner extention setting and make sure <Code-runner: Run In Terminal>
checked
int main(){ char midInitial;
printf("What is your middle initial? ");
scanf(" %c", &midInitial);
printf("Middle inital %c ", midInitial); (see it should be %c)
}

Program output in wrong order

I working on a C project in Eclipse environment the code is correct and executable but the output
lines are not in order the program ask user to
enter a number from 1-5 then asks for a name then street
but nothing appear on console screen unless i entered these values
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char name[20], address[30];
char c;
printf("How do you feel on a scale of 1-5?");
c = getchar();
printf("Enter name: ");
scanf("%s", &name);
printf("Enter your address: ");
scanf("%s", &address);
printf("Entered Name: %s\n", name);
printf("Entered address:%s\n", address);
printf("You said you feel: ");
putchar(c);
return EXIT_SUCCESS;
}
The problem is that stdout is line buffered (when going to a console), so unless you print a newline character, the output will remain buffered and not be displayed (OK, there's going to be a maximum size that can be buffered put that's just detail, your small amount of output will remain in buffer).
The two solutions that occur to me are, use fflush (stdout); after your first 3 printf calls, this will cause the stdout buffer to be flushed to the console, and should resolve your problems.
You could also turn off buffering of stdout, see setvbuf for how to do this, but I think, placing this call near the start of main (before any output) should work (untested):
setvbuf (stdout, NULL, _IONBF, 0);
The problem is your second scanf is capturing the \n character of the previous input, try to use fgets in order to avoid this behaviour.

Printf inserts % at the end of the line

I'm writing a basic program to learn how to use basic input/output in C, and it works just fine. The only problem I have is when it prints, there is a "%" at the end of the string on the terminal. Here's my code:
#include <stdio.h>
int main(int argc, char **argv) {
char name[32];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s", name);
return 0;
}
When I run the program, the output is Hello, Andrew%
Any help?
There's nothing in your code that should explain this behavior. However, it seems likely that if you are running this from a shell, that may be your shell prompt.
Add a newline to your output:
printf("Hello, %s\n", name);
This should cause the prompt to print on the next line as you probably expected.
The stdout stream is line buffered. What this means is the output does not appear on the console until a newline is output or the buffer is full. This may be a cause why you are seeing a % on the screen. '\n' causes printf to print the output immediately on the screen.
Note that if the input string is larger than 31 characters, then scanf will overrun the buffer name invoking undefined behaviour. This may crash the program due to segfault. You should safeguard against it by providing the maximum field width which should be 1 less than the array length to accommodate for the terminating null byte added by scanf.
#include <stdio.h>
// if your not using command line argument, use the below
// signature of main
int main(void) {
char name[32];
printf("Enter your name: \n"); // add a newline to output
scanf("%31s", name); // -1 for the terminating null byte
printf("Hello, %s\n", name); // add a newline to output
return 0;
}
As you have not output a new line - that is your shell prompt character being shown after the specified output. Try printf("Hello, %s\n", name);
Run this command line PROMPT_EOL_MARK='' into your zsh shell, that should be enough to fix it.

C - Not printing out the whole string

int main()
{
//Define Variables
char studentName;
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
scanf("%s", &studentName);
printf("\n\n%s", &studentName);
return 0;
}
Seeing the above code, I am only printing to screen out the first word when I type in a sentence.
I know it is a basic thing, but I am just starting with plain C.
Read scanf(3) documentation. For %s is says
s Matches a sequence of non-white-space characters; the next
pointer must be a pointer to character array that is long
enough to hold the input sequence and the terminating null
byte ('\0'), which is added automatically. The input string
stops at white space or at the maximum field width, whichever
occurs first.
So your code is wrong, because it should have an array for studentName i.e.
char studentName[32];
scanf("%s", studentName);
which is still dangerous because of possible buffer overflow (e.g. if you type a name of 32 or more letters). Using %32s instead of %s might be safer.
Take also the habit of compiling with all warnings enabled and with debugging information (i.e. if using GCC with gcc -Wall -g). Some compilers might have warned you. Learn to use your debugger (such as gdb).
Also, take the habit of ending -not starting- your printf format string with \n (or else call fflush, see fflush(3)).
Learn about undefined behavior. Your program had some! And it misses a #include <stdio.h> directive (as the first non-comment significant line).
BTW, reading existing free software code in C will also teach you many things.
There are three problems with your code:
You are writing a string into a block of memory allocated for a single character; this is undefined behavior
You are printing a string from a block of memory allocated for a single character - also an undefined behavior
You are using scanf to read a string with spaces; %s stops at the first space or end-of-line character.
One way to fix this would be using fgets, like this:
char studentName[100];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
fgets(studentName, 100, stdin);
printf("\n\n%s", &studentName);
return 0;
Try scanf("%[^\n]", &studentName); instead of scanf("%s", &studentName);
This is happening because %s stops reading the input as soon as a white space is encountered.
To avoid this what you can do is declare an array of the length required for your string.
Then use this command to input the string:-
scanf("%[^\n]s",arr);
This way scanf will continue to read characters unless a '\n' is encountered, in other words you press the enter key on your keyboard. This gives a new line signal and the input stops.
int main()
{
//Define Variables
char studentName[50];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
scanf("%[^\n]s", &studentName);
printf("\n\n%s", &studentName);
return 0;
}
Alternatively you can also use the gets() and puts() method. This will really ease your work if you are writing a code for a very basic problem.
[EDIT] : As dasblinkenlight has pointed out...I will also not recommend you to use the gets function since it has been deprecated.
int main()
{
//Define Variables
char studentName[50];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
gets(studentName); printf("\n\n");
puts(studentName);
return 0;
}
make the changes below and try it. I added [80] after the studentName definition, to tell the compiler that studentName is an array of 80 characters (otherwise the compiler would treat it as only one char). Also, the & symbol before studentName is not necessary, because the name of the array implicitly implies a pointer.
int main()
{
//Define Variables
char studentName[80];
//Print instructions to fill the data in the screen
printf("Please type in the Students name:\n");
scanf("%s", studentName);
printf("\n\n%s", studentName);
return 0;
}
Your problem is here
char studentName;
It is a char, not a string.
Try:
Define it as an array of chars like char studenName[SIZE];.
allocating memory dynamically using malloc:
.
char buffer[MAX_SIZE];
scanf("%s", &buffer);
char * studentName = malloc (sizeof(buffer) + 1);
strcpy (studentName , buffer);

Resources