How to assign new string values in C [duplicate] - c

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

Related

C programming scanf assistance

I am attempting to build a form/gpa calculator for class, but when entering the amount of classes using scanf, the output is 6,487,576 regardless of what I enter.
int main()
{
int opt;
int c;
printf("*******************************\n");
printf("** Fanshawe Grade Calculator **\n");
printf("*******************************\n");
printf("Please Choose an Option:\n");
printf("[1] Enter Your Marks\n");
printf("[2] Quit\n");
scanf("%d", &opt);
switch(opt) {
case 1 :
printf("********************************************************\n");
printf("** Enter Your Marks For Your Courses (Up to 10 Only): **\n");
printf("********************************************************\n");
scanf("%i", &c);
printf("You Have Entered %i Classes!\n", &c);
/*int i;
for(i=1;i=c;i++) {
printf("Enter Your Mark for Class #%i\n", &i);
}*/
break;
case 2 :
printf("GoodBye!");
exit(0);
break;
}
return 0;
}
Help please!
When you use %i with scanf(), it can allow you to input hexadecimal and octal numbers as well (this isn't an issue as explained here).
However, you shouldn't use & while using printf() as it'll display the memory location of the variable instead of the value stored in it.
Try this:
case 1 :
printf("********************************************************\n");
printf("** Enter Your Marks For Your Courses (Up to 10 Only): **\n");
printf("********************************************************\n");
scanf("%d", &c);
printf("You Have Entered %d Classes!\n", c);
break;
printf("You Have Entered %i Classes!\n", &c) outputs the address of the variable c (&c takes the address), i.e. it outputs the number of the memory cell. Since you want to pass the value of the variable you should not use the operator of taking address of a variable &.
printf("You Have Entered %i Classes!\n", c);
There are two problems here. First, you need to include the following headers:
#include <stdio.h> // declares functions like printf and scanf
#include <stdlib.h> // declares functions like exit
If you don't include these headers, then the compiler does not know how to execute them or their exact formats. When you attempt to compile, the warnings will not be helpful. There are a few good websites for this; just search something like "c exit()" in Google and it will tell you which headers you need in the future. When I compiled this code, I used gcc main.c -Wall which forces all warnings to be displayed.
Secondly, you use the address of c in both cases. When you go to print the value of c, you are actually printing the address of c, not the value. scanf() takes the address(es) of the variables to store values in, but printf() takes the variables themselves. The code should look more like this:
scanf("%i", &c);
printf("You Have Entered %i Classes!\n", c);
It is also always a good idea to initialize your variables. This way, you know when something is assigned improperly, or not assigned at all. I forgot to assign my variables for a while, and when compiled on another machine, it didn't work. This is because different machines will initialize variables differently. Just change the code to the following:
int opt = 0;
int c = 0;

C- Incorporating realloc with string pointers

I'm working on a problem about modifying strings with dynamic memory allocation. The applicable parts of my code are as follows:
./dma 5
#include <stdio.h>
#include <stdlib.h>
char* strcopy(char* destination, char* source);
char *strconcat(char* destination, char* source);
int main(int argc, char *argv[]) {
int cmd, a=1, b, length_of_str, n, n2;
char* pstring[atoi(argv[1])];
for (b=0; b<atoi(argv[1]); b++) {
printf("Enter the length of string %d: ", b+1);
scanf("%d", &length_of_str);
pstring[b]=(char *)malloc(length_of_str*sizeof(char));
printf("Please enter string %d: ", b+1);
scanf("%s", &pstring[b]);
}
while (a!=0) {
printf("Your strings are: \n");
for (b=0; b<atoi(argv[1]); b++) {
printf("String number %d - \"%s\"\n", b+1, &pstring[b]);
}
printf("Options:\n");
printf("1 - Find string length\n");
printf("2 - Compare strings\n");
printf("3 - Copy strings\n");
printf("4 - Concatenate strings\n");
printf("5 - Quit\n");
printf("Please enter your option: ");
scanf("%d", &cmd);
switch (cmd) {
case 3:
printf("Enter the number of the source string: ");
scanf("%d", &n);
printf("Enter the number of the destination string: ");
scanf("%d", &n2);
strcopy(pstring[n-1], pstring[n2-1]);
break;
case 4:
printf("Enter the number of the source string: ");
scanf("%d", &n);
printf("Enter the number of the destination string: ");
scanf("%d", &n2);
strconcat(pstring[n-1], pstring[n2-1]);
break;
case 5:
a=0;
break;
default:
printf("Invalid Option.\n");
break;
}
}
free(pstring);
return 0;
}
char* strcopy(char* destination, char* source) {
destination=(char *)realloc(*source, sizeof(char)*strlength(destination));
for (; *source!='\0'; source++) {
*destination=*source;
destination++;
}
*destination='\0';
return destination;
}
char* strconcat(char* destination, char* source) {
destination=(char *)realloc(*source, sizeof(char)*strlength(destination));
for (; *destination!='\0'; destination++) {
}
for (; *source!='\0'; source++) {
*destination=*source;
destination++;
}
*destination='\0';
return destination;
}
I need to incorporate realloc into my concatenation and copy functions (which should be fine since they worked in a separate problem). I've tried a number of ways and I've tried different syntax but I only seem to get segmentation faults or invalid pointers. How exactly am I supposed to incorporate realloc? The intended result should look like this:
Your strings are:
String number 1 – “first”
String number 2 – “second”
String number 3 – “third”
String number 4 – “fourth”
String number 5 – “fifth”
Options:
1 – Find string length
2 – Compare strings
3 – Copy strings
4 – Concatenate strings
5 – Quit
Please enter your option: 3
Enter the number of the source string: 2
Enter the number of the destination string: 5
Your strings are:
String number 1 – “first”
String number 2 – “second”
String number 3 – “third”
String number 4 – “fourth”
String number 5 – “second”
Options:
1 – Find string length
2 – Compare strings
3 – Copy strings
4 – Concatenate strings
5 – Quit
Please enter your option:
One major problem is how you read the string:
scanf("%s", &pstring[b])
Here pstring[b] is of type char *, and due to the malloc call it points to some memory (unless malloc fails, which you forget to check for).
But &pstring[b] is a pointer to the pointer, and is of type char **. This is hardly what you want, and will cause scanf to write to memory somewhere it wasn't supposed to write, and can even write out of bounds of allocated memory. This of course leads to undefined behavior.
Once you solve that, you need to remember that char strings in C are really called null-terminated byte strings. The null-terminator is what all standard string functions look for to find the end of the string. Of course, that means that a string for x characters needs space for x + 1 to fit the terminator. So if the user says he or she want a string of length 6 (for example) and then give foobar as input, that needs space for 7 characters with the terminator. This terminator problem (or rather missing to allocate space for it) you have in other places as well (like the strcopy function).
Your scanf call also doesn't hinder the user to input a string longer that the user said. If the user said that the string should be 3 characters, but then enter foobar, that will write out of bounds. Unfortunately there's no way to solve this with only scanf, as the field width modifier must be part of the format string. You could use the scanf_s function which solves this problem, but it's not mandated by the C specification, and needs you to define a specific macro for it to be available if the implementation have it (see e..g this scanf and family reference for details). Otherwise you need to programatically construct the format string to include a field width.
You also do free(pstring) which is invalid, since you didn't allocate pstring itself, it's an array. You do need to loop over all the strings in the array pstring and free them. Trying to pass a pointer not returned by malloc (et al) to free also leads to undefined behavior.
Lastly, in C you should not cast the result of malloc (and related functions).

How Can I replace this type "int" by"String" in c programming? [duplicate]

This question already has answers here:
How do I check if a value matches a string
(4 answers)
Closed 6 years ago.
I'm using dev c++ . This is silly program which ask the correct key to show a text. This program working perfectly with type "int" (just numbers):
#include <stdio.h>
#include<conio.h>
main()
{
int key;
printf("This program show a mensage if you get the correct key \n");
printf("Write the key:\n");
scanf("%i",&key);
if(key==1234)
{
printf("Welcome to stackoverflow \n");
}
else
{
printf("You keep going slept \n");
}
getch();
return 0;
}
But How can I replace for strings for example: sesame, house and so on.
I've tried by matrix:
char key[];
However i get Error.
Sincerily
NIN.
Update:
I could get a new program :
#include <stdio.h>
#include<conio.h>
main()
{
char key[7]; /*replace int for char*/
printf("This program show a mensage if you get the correct key \n");
printf("Write the key:\n");
scanf("%c",&key);
if(key=="sesame") /*numbers for string*/
{
printf("Welcome to stackoverflow \n");
}
else
{
printf("You keep going slept \n");
}
getch();
return 0;
}
However even though I fix the correct key ("sesame") I just get "You keep going slept"
You cannot compare value of strings using == operator
if(key=="sesame") // This compares pointers
You need
if(strcmp(key,"sesame") == 0)
See: http://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm
Also
scanf("%c",&key);
will not work. %c gets only 1 character.
You need %s for string.
int ret = scanf("%6s", key); // or scanf("%6s", &key[0]);
if (ret < 0)
{
// The function returns the number of input items successfully matched and assigned,
// which can be fewer than provided for, or even zero in the event of an early matching failure.
// The value EOF is returned if the end of input is reached before either the
// first successful conversion or a matching failure occurs. EOF is also returned
// if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
// see: http://linux.die.net/man/3/scanf
}
Note that you need just key or &key[0] as a pointer to the key buffer.
Problem 1:
scanf("%c",&key);
is not right. It will read just one character. You need to use
scanf("%6s", key);
Problem 2:
if(key=="sesame")
is not the proper way to compare two strings. It will compare two pointers and will evaluate to false. You need to use:
if( strcmp(key, "sesame") == 0 )
#include <stdio.h>
int main()
{
char *a = "sesame";
printf("this program show a message if you get the correct key \n");
printf("write the correct key:\n");
// scanf("%c",&key);
if(a == "sesame")
{
printf("welcome to stack overflow \n");
}
else
{
printf("you keep going to sleep \n");
}
return 0;
}

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

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).

how to comb through an input (equation) and grab variables, disregarding whitespace? (scanf()), (arrays)

For my C program, the user enters in "aY + b = c" where a, b, and c are int values and Y is a "symbolic constant."
How does one make it so that "aY+b=c" works as well as "aY + b = C" works? Basically, I am unsure of how to utilize scanf() so that I can grab my variables a,b, and c from the user input no matter how many spaces the user decides to input.
Thanks!
Consider the following:
Code
#include <stdio.h>
#include <ctype.h>
#define MAX_EQUATION_LEN (1000)
int main(void)
{
char equation[MAX_EQUATION_LEN];
int num, i;
printf("Enter a equation: ");
fgets(equation, MAX_EQUATION_LEN, stdin);
sscanf(equation, "%d", &num);
i = 0;
while(equation[i])
{
if(!isdigit(equation[i]))
break;
else
i++;
}
printf("You entered: %d\n", num);
printf("Unhandled string data: %s\n", &equation[i]);
return 0;
}
Example Run
Enter a equation: 204Y + 52 = 9
You entered: 204
Unhandled string data: Y + 52 = 9
Logic
Take the full equation in at one time as a string.
Parse the string accordingly. Here, I'm looking for the first int.
Keep track of where you are in the string parsing process.
Keep parsing the string until there are no more characters.
I am unsure of how to utilize scanf() so that I can grab my variables a,b, and c from the user input no matter how many spaces the user decides to input.
Don't use scanf in the first place. You need to write a lexer and a parser, so write a lexer and a parser.

Resources