CodeBlocks exe stops working - c

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char string;
printf("Hello\n");
printf("What would you like to do\n");
printf("Here are the options\n");
printf("s : How are you\n");
printf("c : What would you like to search\n");
scanf("%s",&string);
if(string == 'h')
printf("iam fine\n");
else if (string == 's')
printf("What would you like to search\n");
scanf("%s",&string);
system(string);
return 0;
}
When I run this after it says what would you like to search and I type run notepad it stops working.

There are two problems with this scanf:
printf("What would you like to search\n");
scanf("%s",&string);
system(string);
string is a single char - the scanf will result in a buffer overrun.
The %s format specifier only reads until the next whitespace.
To fix the problem you should allocate a larger buffer and read an entire line:
char buffer[1024];
printf("What would you like to search\n");
fgets(buffer, sizeof buffer, stdin);
system(buffer);

Problem 1. defining string as char won't work for you. you need an array.
define char string[100] = {0};
Problem 2. scanf("%s",&string); not required, can be used as scanf("%s",string);
problem 3. if(string == 'h'), wrong. array contents cannot be compared using == operator. you've to use strcmp() function.

Related

2D character array in C [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
In C:
I'm trying to get char from the user with scanf and when I run it the program don't wait for the user to type anything...
This is the code:
char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c\n",ch);
Why is not working?
The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.
One way around the problem is to put a blank space before the conversion specifier in the format string:
scanf(" %c", &c);
The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.
First of all, avoid scanf(). Using it is not worth the pain.
See: Why does everyone say not to use scanf? What should I use instead?
Using a whitespace character in scanf() would ignore any number of whitespace characters left in the input stream, what if you need to read more inputs? Consider:
#include <stdio.h>
int main(void)
{
char ch1, ch2;
scanf("%c", &ch1); /* Leaves the newline in the input */
scanf(" %c", &ch2); /* The leading whitespace ensures it's the
previous newline is ignored */
printf("ch1: %c, ch2: %c\n", ch1, ch2);
/* All good so far */
char ch3;
scanf("%c", &ch3); /* Doesn't read input due to the same problem */
printf("ch3: %c\n", ch3);
return 0;
}
While the 3rd scanf() can be fixed in the same way using a leading whitespace, it's not always going to that simple as above.
Another major problem is, scanf() will not discard any input in the input stream if it doesn't match the format. For example, if you input abc for an int such as: scanf("%d", &int_var); then abc will have to read and discarded. Consider:
#include <stdio.h>
int main(void)
{
int i;
while(1) {
if (scanf("%d", &i) != 1) { /* Input "abc" */
printf("Invalid input. Try again\n");
} else {
break;
}
}
printf("Int read: %d\n", i);
return 0;
}
Another common problem is mixing scanf() and fgets(). Consider:
#include <stdio.h>
int main(void)
{
int age;
char name[256];
printf("Input your age:");
scanf("%d", &age); /* Input 10 */
printf("Input your full name [firstname lastname]");
fgets(name, sizeof name, stdin); /* Doesn't read! */
return 0;
}
The call to fgets() doesn't wait for input because the newline left by the previous scanf() call is read and fgets() terminates input reading when it encounters a newline.
There are many other similar problems associated with scanf(). That's why it's generally recommended to avoid it.
So, what's the alternative? Use fgets() function instead in the following fashion to read a single character:
#include <stdio.h>
int main(void)
{
char line[256];
char ch;
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
return 0;
}
One detail to be aware of when using fgets() will read in the newline character if there's enough room in the inut buffer. If it's not desirable then you can remove it:
char line[256];
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
line[strcpsn(line, "\n")] = 0; /* removes the trailing newline, if present */
This works for me try it out
int main(){
char c;
scanf(" %c",&c);
printf("%c",c);
return 0;
}
Here is a similiar thing that I would like to share,
while you're working on Visual Studio you could get an error like:
'scanf': function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
To prevent this, you should write it in the following format
A single character may be read as follows:
char c;
scanf_s("%c", &c, 1);
When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.
char c[4];
scanf_s("%4c", &c, _countof(c));
neither fgets nor getchar works to solve the problem.
the only workaround is keeping a space before %c while using scanf
scanf(" %c",ch); // will only work
In the follwing fgets also not work..
char line[256];
char ch;
int i;
printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
try using getchar(); instead
syntax:
void main() {
char ch;
ch = getchar();
}
Before the scanf put fflush(stdin); to clear buffer.
The only code that worked for me is:
scanf(" %c",&c);
I was having the same problem, and only with single characters. After an hour of random testing I can not report an issue yet. One would think that C would have by now a bullet-proof function to retrieve single characters from the keyboard, and not an array of possible hackarounds... Just saying...
Use string instead of char
like
char c[10];
scanf ("%s", c);
I belive it works nice.
Provides a space before %c conversion specifier so that compiler will ignore white spaces. The program may be written as below:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Enter one char");
scanf(" %c", &ch); /*Space is given before %c*/
printf("%c\n",ch);
return 0;
}
You have to use a valid variable. ch is not a valid variable for this program. Use char Aaa;
char aaa;
scanf("%c",&Aaa);
Tested and it works.

How to save a string with multiple words with scanf()

I just started programming in C and I was wondering why I can't store a string with multiple words with scanf().
For example, I enter: "That's an example" and it's stores only the first word "That's"
My code:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", &string);
printf("You entered: %s", string);
return (0);
}
You can let scanf() read more than one word with the character class conversion specifier: %[^\n] will stop at the newline and leave it pending in the input stream. Note that you must tell scanf the maximum number of characters to store into the destination array to avoid undefined behavior on long input lines. When passing an array to scanf(), you should not pass its address as &string, but just pass string as arrays decays into a pointer to their first element when passed as a function argument.
Here is a modified version:
#include <stdio.h>
int main(void) {
char string[100];
int c;
for (;;) {
printf("Please enter something: ");
/* initialize `string` in case the `scanf()` conversion fails on an empty line */
*string = '\0';
if (scanf("%99[^\n]", string) == EOF)
break;
printf("You entered: %s\n", string);
/* read the next byte (should be the newline) */
c = getchar();
if (c == EOF) /* end of file */
break;
if (c != '\n')
ungetc(c, stdin); /* not a newline: push it back */
}
return 0;
}
Note however that it is much simpler to use fgets() for this task:
#include <stdio.h>
int main(void) {
char string[100];
for (;;) {
printf("Please enter something: ");
if (!fgets(string, sizeof string, stdin))
break;
/* strip the trailing newline, if any */
string[strcspn(string, "\n")] = '\0';
printf("You entered: %s\n", string);
}
return 0;
}
#include <stdio.h>
#define BUFF_SIZE 512
int main(void) {
char string[BUFF_SIZE];
printf("Enter something: ");
fgets(string, BUFF_SIZE, stdin);
printf("You entered: %s", string);
return (0);
}
fgets() is the best option
I think there's a problem in you scanf(); I recommend you to remove & from it. then your code should see like that:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", string);
printf("You entered: %s", string);
return (0);
}
In the c language, there is no data type called a string.
A string is stored as an array of characters.
Moreover, the variable itself points to the first element of the array. Therefore, there is no need to use the '&' operator to pass the address.
So, all you have to do is the following:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", string);
printf("You entered: %s", string);
return (0);
}
Don't use '&' in scanf function.
int main()
{
char string[100];
printf("Please enter something: ");
scanf("%[^\n]%*c",string);
printf("You entered: %s", string);
return 0;
}
According to https://man7.org/linux/man-pages/man3/scanf.3.html, %s will ignore white-space characters. To capture spaces you would have to use %c with the additional size of the input argument, or use %[ format. Check if scanf will add \0 byte to the end or not.

How to extract the string after a word in C

I am trying to add a functionality in my program that gets the specific word or sentence after a particular word in C.
E.g.
When I try to type:
"say Hello World", the program will print "Hello World" only.
My code runs like this:
int main(){
char command;
do{
printf("MyOS>");
scanf("%s", &command);
if(strncmp(&command, "say", 3) == 0){
//enter code here
}
} while (strncmp(&command, "exit", 4));
return 0;
}
when running, the program asks for an input string, and in the case that my string starts with "say", I want it to output the next words/string.
You have two problems
scanf("%s", &command); here variable command requires a buffer of some size greater than 1.
Use as below
#define COMMAND_SIZE 1024 and declare some thing like char command[COMMAND_SIZE] = {0}
I think you are trying to read multiword string, that is not possible with the way you used scanf("%s", command); even if command has sufficient size.
Better use fgets(command, sizeof(command), stdin); to read multiword strings.
In short you need some thing like this:
#include <stdio.h>
#include <string.h>
#define COMMAND_SIZE 512
int main(){
char command[COMMAND_SIZE] = {0};
do{
printf("MyOS>");
fgets(command,sizeof (command), stdin);
if(strncmp(command, "say", 3) == 0) {
printf(" %s\n", command+3);
}
} while (strncmp(command, "exit", 4));
return 0;
}
Note: Make sure you allocate sufficient buffer to store your input command, and enter the input which is less than COMMAND_SIZE characters , so that it will have enough space the \n, else you will face problems with leftover \n characters.

Getting specific # of characters

I want to get only 2 characters in my program. I tried fgets but I can get it to work. How do you suggest that I implement this? Or is there any alternative?
char code[2];
printf("Enter code: \n");
scanf("%s", code);`
I want to limit the number of characters that can be entered to two.
To read two characters and ignore white space you can do:
#include <stdio.h>
int main() {
char code[2];
printf("Enter code:\n");
if (scanf(" %c %c", &code[0], &code[1]) == 2) {
printf("successfully read '%c' and '%c'\n", code[0], code[1]);
}
return 0;
}
to not ignore white space use "%c%c" as the format.
Try this code
#include<stdio.h>
#include<conio.h>
void main()
{
char code;
clrscr();
printf("enter the code\n");
scanf("%2s",code);
printf("%s",code);
getch();
}

Input problems scanf()/getchar()

I am making a text based game, and i am having a big problem with input. Here is a small example of my problem code.
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
}
return 0;
}
So, if you compile/run this, and type in 'abc', it will just take each one, and send it through the loop. What I need it to do is only take the very first character that someone types in, no matter how many they do type in.
And, PS: I have tried it this way, and it does the same thing:
#include <stdio.h>
#include <stdlib.h>
char c[2];
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
scanf("%1s", c);
printf("\nYour input: %c\n", c[0]);
sleep(1);
system("clear");
}
return 0;
}
EDIT: It also adds a space to what ever you type in, I assume it is a \0, but im not sure. Thanks!
When you use scanf, enter a string and hit the ENTER key, a string and a character are placed in the input buffer, they are namely: the entered string and the newline character. The string or character by character gets consumed by the scanf but the newline remains in the input buffer, unless you consume that too.
getchar(), on the other hand will not wait for ENTER key, it would read character by character, then your logic.
I think you can add 1 more line to read all the characters that come after the first one until there is a newline character (i.e. the user presses Enter):
while (getchar() != '\n');
Adding to your example, it would be like this:
#include <stdio.h>
#include <stdlib.h>
char c;
int main(int argc, char *argv[]){
system("clear");
while(1){
printf("\nInput a character.\n");
c = getchar();
printf("\nYour input: %c\n", c);
sleep(1);
system("clear");
while (getchar() != '\n');
}
return 0;
}
Use getch() which does not wait for a newline.
What i think you look for is something like this code, to save very first character, you can also check if c == '\n' to continue your operation, but i dont know what you want after saving very first character:
int i,c;
char save;
for ( i = 0;(c=getchar())!= EOF ; i++)
{
if ( i == 0)
save = c;
}
You can use fgets(), and extract its first character, like...
char ch[2], c;
fgets(ch, 2, stdin);
c = ch[0];

Resources