What is causing my print statements to produce different results? [duplicate] - c

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 6 years ago.
I'm a newbie learning to program in C, and I am currently working on creating a program that takes a name input from a user then prints that name back on to the screen. When the program prints out the name in the else if block, what I get is $ ". I want to know why it happens and how I might correct this problem. My code is as follows:
#include <stdio.h>
#include <stdlib.h>
int main() {
char * ans; // yes/no answer
char * name; //name variable
printf("Welcome to the program. Would you like to begin? (y/n)\n");
scanf("%s", ans);
if (strcmp(ans, "y") != 0) {
printf("Have a good day!\n");
return 0;
}
else if (strcmp(ans, "y") == 0)
printf(" %s\n", ans);
printf("Okay, input your name:\n");
scanf("%s", name);
printf(" %s", name);// I get $ " rather than the name.
return 0;
}

You are using scanf() to read characters from the user, but haven't allocated any memory to hold those characters. This gives undefined behavior, as "anything can happen" when you break the rules like that.
Make those uninitialized pointers into arrays instead:
char ans[128];
char name[128];
This gives you 128 characters of space for each string (one of which will be used by the terminator).

Related

The program is not able to print all the words. I am facing this issue with many program. eg -to compute the frequency of the words [duplicate]

This question already has answers here:
Scanf reads only one word from sentence
(4 answers)
Closed 1 year ago.
#include<stdio.h>
#include<string.h>
int main(){
char sen[100];
int i=0,len;
printf("Enter a senetence\n");
scanf("%s",sen);
len=strlen(sen);
char ch=sen[i];
while(i<len){
if(ch==' '){
printf("\n");
i++;
ch=sen[i];
continue;
} //i dont know what is the flaw with the logic.
printf("%c",ch);
i++;
ch=sen[i];
}
return 0;
}
The aim of the program is to print the words of a sentence separately. However, this program is successful in printing only the first word. Please tell me where I am going wrong.
You get just one word as input. You can scanf the input like:
scanf("%[^\n]s",sen);

I am trying to write a program that stops with a specific string input [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 1 year ago.
I am just starting to learn C coding ,I am trying to write a program that keeps scanning names and once it scans a specific name lets say for example "John" it stops Please correct me
#include <stdio.h>
int main()
{
char name[20];
printf("enter a name:");
for(;;)
{
scanf("%s",name);
if (name='John')
{
break;
}
}
You can't compare two string pointers with != or ==.
you need to use strcmp, for example:
while (strcmp(check,input) != 0)
strcmp compares the string pointed to, by str1 to the string pointed to by str2.

C: Segmentation fault after trying to print data on screen [duplicate]

This question already has answers here:
Why does scanf require &?
(7 answers)
When should I use ampersand with scanf()
(3 answers)
Closed 4 years ago.
I'm new to C language and having this problem alot, the code compiles with no problems yet still get this message: Segmentation fault
when trying to execute my code on UNIX terminal.
This is the code:
///MAIN FUNCTION///
int main() {
printf("==========================J.U.S.T=======================$
printf("Enter your option number:\n1- working with an existing f$
char choice[1];
scanf("%c",choice);
if(choice[0] == '1'){
printf("first choice");
}
else if(choice[0] =='2' ){
printf("Enter the following data one by one:");
char BookT[50],AUTHORn[50];long int ISBN;
printf("Book Title:");
scanf("%s",BookT);
// sleep(5);
printf("Author name:");
scanf("%s",AUTHORn);
// sleep(5);
printf("Book number:");
scanf("%d",ISBN);
// sleep(5);
printf("%s\n%s\n%d\n",BookT,AUTHORn,ISBN);
}
else printf("Wrong choice try again!!");
return 0;
}
I'm using Kali linux to compile the code.
As you probably have noticed, the segmentation fault happens at the line
scanf("%d",ISBN);
scanf requires a pointer to save the result in, but you are passing it the value of the variable ISBN. In order to save the result in the ISBN variable you should send it a pointer to the variable instead: scanf("%d", &ISBN);
(arrays already work (more or less) the same way as pointers, so there is no need to use & when reading strings)
You should add an ampersand and proper format specifier to scanf scanf("%ld",&ISBN);
Just change the line scanf("%d", ISBN); by scanf("%d", &ISBN); , scan requires a pointer and you are trying to save the result without pointer, so the program will just segfault. But if you give him the adress of the variable, he can reach it and save the result in it.

How to assign new string values in C [duplicate]

This question already has answers here:
Assigning strings to arrays of characters
(10 answers)
Closed 5 years ago.
My simple calculator is trying to display the chosen operation of the user. I understand that in C, strings must be declared as 1D char arrays.
int a, b;
int oper; //operation number
char operName[15];
printf("\nEnter two numbers: ");
scanf("%d%d", &a, &b);
printf("\nYou entered: %d and %d", a, b);
printf("\nChoose operation:"
"\n1 = +"
"\n2 = -"
"\n3 = x"
"\n4 = /");
scanf("%d", &oper);
The code compiles and runs. But when executing the switch block, it stops working. I'm using switch to choose the appropriate operation name, and assign it to operName (so I can display the chosen operation before I do the actual operation).
switch(oper){
case 1:
operName == "Addition";
break;
.
.
.
default:
operName == "Invalid input";
}
printf("\n\nYou chose: %s", oper);
I read somewhere that I need to use pointers to prevent memory leaks, but I'm new to this so maybe there's an easier way.
The == is not for assignment. C is a pretty low level language you can not assign values to strings in C like you would for an integer or a character.
To do so you must use the standard library string.h.
For instance:
#include <stdio.h>
#include <string.h>
int main(void)
{
char source[1000], destination[1000];
/* Do something with the strings */
strcpy(destination, source);
return 0;
}
Find out more about string.h here

scanf and char pointers in C -- unexpected output [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
void main(int argc, char * argv[])
{
FILE* inFile = NULL;
char * bufferFromStdin;
char buf[100];
printf("Enter something:\n");
scanf("%s", buf);
printf("First scan from stdin is: %s\n", buf);
if(buf == "THIS" || buf[0]=='T')
{
printf("THIS found first\n");
}
else {printf("Not Found first\n");}
printf("Enter something again:\n");
scanf("%s", bufferFromStdin);
printf("Second scan from stdin is: %s\n", bufferFromStdin);
if(bufferFromStdin == "THIS")
{
printf("THIS found second\n");
}
else {printf("Not Found second\n");}
}//main
gives me the output:
./test < testinput.txt
Enter something:
First scan from stdin is: THIS
THIS found first
Enter something again:
Second scan from stdin is: (null)
Not Found second
testinput.txt has one line of text "THIS"
this is what I get when I run the program with input as regular stdin
./test
Enter something:
THIS
First scan from stdin is: THIS
THIS found first
Enter something again:
THIS
Second scan from stdin is: (null)
Not Found second
How come the input cannot be saved to a char* when using either input method and how would I work around this? I need to get input from stdin by the keyboard and redirecting I/O as well. I think it's something to do with malloc();
Thanks for the help.
You have two critical errors in your code. First of all, bufferFromStdin does not point to allocated memory. scanf requires a pointer to memory that has been previously allocated (such as buf in your example) where it will store the result. When you pass an uninitialized variable such as bufferFromStdin the result is undefined.
Second, the == operator in C compares two pointers, not what they are pointing to. Therefore, buf == "THIS" will never be true, since buf isn't pointing to a constant array. In order to compare two strings, use strcmp. Of course, both pointers need to point to something for this to work.
Also, as a side note, main should always return int not void.
Once you correct those two problems, your code should work:
int main(int argc, char * argv[])
{
char buf[100];
printf("Enter something:\n");
scanf("%s", buf);
printf("First scan from stdin is: %s\n", buf);
if(strcmp(buf, "THIS") == 0) {
printf("THIS found first\n");
} else {printf("Not Found first\n");}
return 0;
}
you have a couple of programming errors in your code.
void main(int argc, char * argv[])
{
FILE* inFile = NULL;
char * bufferFromStdin;
char buf[100];
you are allocating three pointer variables, using three different styles:
inFile is properly initialized (NULL pointer).
bufferFromStdin is not initialized.
buf is initialized and points to a statically allocated area.
you probably want to check how one allocates memory in C.
printf("Enter something:\n");
scanf("%s", buf);
this scanf call is just a bit dangerous. if the user inserts a string that is longer than 99 chars (remember the \0 terminator), it will overflow the buffer. you probably want to check this question.
printf("First scan from stdin is: %s\n", buf);
if(buf == "THIS" || buf[0]=='T')
I'm sorry to say, but I find this quite funny! you want to test string equality (content, not pointer) and you see the first test does not work (you are comparing pointers) so you add a second test. check the manual pages.
{
printf("THIS found first\n");
}
else {printf("Not Found first\n");}
I find this also a bit ugly. you might want to stick to one style for indenting.
printf("Enter something again:\n");
scanf("%s", bufferFromStdin);
you are using your uninitialized pointer. what happens here depends on your programming environment, operating system, compiler. a strong operating system will probably terminate your program. or you are corrupting some memory areas.
printf("Second scan from stdin is: %s\n", bufferFromStdin);
if(bufferFromStdin == "THIS")
same problem as above, but you forgot to implement your workaround.
{
printf("THIS found second\n");
}
else {printf("Not Found second\n");}
}//main

Resources