This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
I'm a beginner in c programming and i'have come to a point (pretty ridiculous) that i'm stuck at an if statement between two strings.
In this program, i want the user to input a lesson of a student saved in a structure, then it should search for students with the same lesson and print them on screen.
My problem is at if statement, for some reason (memory address maybe?) when i type the same characters, it sees them for different strings.
The code just "skips" the if part. Although it works when i declare if(record[0].lesson!="maths") for instance.
i have tried lots of things such as strcmp,
if (record[0].lesson==record[1].lesson)
if(record[0].lesson=="maths")... and other.
I would highly appreciate it if you could help me. thank you very much.
# include <stdio.h>
# include <string.h>
typedef struct student{
char name[10];
char lesson[10];
}students;
int main()
{
students record[10];
char less;
strcpy(record[0].name,"James");
strcpy(record[0].lesson,"maths");
strcpy(record[1].name,"John");
strcpy(record[1].lesson,"maths");
strcpy(record[2].name,"Harry");
strcpy(record[2].lesson,"C/C++");
printf("Give Lesson\n");
scanf("%s",less);
for(int i=0;i<3;i++){
if(less==record[i].lesson)
printf("%s\n",record[i].name);}
return 0;
}
You want this:
better formatting
less declared correctly as char less[10];
using strcmp for string comparision instead of ==
#include <stdio.h>
#include <string.h>
typedef struct student{
char name[10];
char lesson[10];
} students;
int main()
{
students record[10];
char less[10];
strcpy(record[0].name, "James");
strcpy(record[0].lesson, "maths");
strcpy(record[1].name, "John");
strcpy(record[1].lesson, "maths");
strcpy(record[2].name, "Harry");
strcpy(record[2].lesson, "C/C++");
printf("Give Lesson\n");
scanf("%s", less);
for (int i = 0; i < 3; i++) {
if (strcmp(less, record[i].lesson) == 0)
printf("%s\n",record[i].name);
}
return 0;
}
There is still much room for improvement.
Related
So I suck with functions and need to debug this. Im pretty sure the function ToPigLating does its job well at converting. However I just need help calling the function ToPigLatin inside of my main function. But when I try doing that I just get a bunch of error codes.
#include <stdlib.h>
#include <string.h>
#define LEN 32
char* ToPigLatin(char* word[LEN]){
char word[LEN];
char translation [LEN];
char temp [LEN];
int i, j;
while ((scanf ("%s", word)) != '\0') {
strcpy (translation, word);
//just pretend I have all the work to convert it in here.
} // while
}
int main(){
printf("Enter 5 words: ");
scanf("%s", word);
ToPigLatin();
}```
Roughly, variables only exist within the function they're declared in. The word in ToPigLatin exists only within ToPigLatin. It is not available in main. This lets us write functions without worrying about all the rest of the code.
You need to declare a different variable in main, it can also be called word, to store the input and then pass that into ToPigLatin.
Let's illustrate with something simpler, a function which doubles its input.
int times_two(int number) {
return number * 2;
}
We need to give times_two a number.
int main() {
// This is different from "number" in times_two.
int number = 42;
// We have to pass its value into time_two.
int doubled = times_two(number);
printf("%d doubled is %d\n", number, doubled);
}
Your case is a bit more complicated because you're working with input and memory allocation and arrays. I'd suggest just focusing on arrays and function calls for now. No scanf. No strcpy.
For example, here's a function to print an array of words.
#include <stdio.h>
// Arrays in C don't store their size, the size must be given.
void printWords(const char *words[], size_t num_words) {
for( int i = 0; i < num_words; i++ ) {
printf("word[%d] is %s.\n", i, words[i]);
}
}
int main(){
// This "words" variable is distinct from the one in printWords.
const char *words[] = {"up", "down", "left", "right"};
// It must be passed into printWords along with its size.
printWords(words, 4);
}
ToPigLatingToPigLating function expects to have a parameter like ToPigLating("MyParameter");
Hello there icecolddash.
First things first, there are some concepts missing. In main section:
scanf("%s", word);
You're probably trying to read a string format and store in word variable.
In this case, you should have it on your declaration scope. After some adjustment, it will look like this:
int main(){
char word[LEN];
As you defined LEN with 32 bytes maximum, your program will not be allowed to read bigger strings.
You're also using standard input and output funcitions as printf, and so you should ever include stdio.h, thats the header which cointains those prototypes already declared, avoiding 'implicit declaration' compiling warnings.
Next issue is how you're declaring your translation function, so we have to think about it:
char* ToPigLatin(char* word[LEN])
In this case, what you wrote:
ToPigLatin is a funcion that returns a char pointer, which means you want your function to probably return a string. If it makes sense to you, no problem at all. Although we got some real problem with the parameter char* word[LEN].
Declaring your variable like this, assume that you're passing an array of strings as a parameter. If I got it right, you want to read all five words in main section and translate each one of them.
In this case I suggest some changes in main function, for example :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 32
#define MAX_WORDS 5
char *globalname = "translated";
char* ToPigLatin(char* word){
char *translation = NULL;
//Translation work here.
if ( !strcmp(word, "icecolddash") ){
return NULL;
}
translation = globalname;
return translation;
}
int main(){
char word[LEN];
char *translatedword;
int i;
printf("Enter 5 words: \n");
for ( i=0; i < MAX_WORDS; i++ ){
fgets(word, sizeof(word), stdin);
strtok(word, "\n"); // Just in case you're using a keyboard as input.
translatedword = ToPigLatin(word);
if ( translatedword != NULL ){
//Do something with your translation
//I'll just print it out as an example
printf("%s\n", translatedword);
continue;
}
// Generic couldn't translate message
printf("Sorry, I know nothing about %s\n", word);
}
return 0;
}
The above code translate every word in a fixed word "translated".
In case of reading the exact input "icecolddash", the program will output a generic error message, simulating some problem on translation process.
I hope this help you out with your studies.
There are a few things that I see.
#include <stdio.h>
#include <stdlib.h>
char* ToPigLatin(char* word){
printf(word);
return word;
}
int main(){
printf("Enter 5 words: ");
// declare the variable read into by scanf
char * word = NULL;
scanf("%s", word);
//Pass the variable into the function
ToPigLatin(word);
// Make sure you return an int from main()
return 0;
}
I left some comments in the code with some specific details.
However, the main thing that I would like to call out is the style of the way you're writing your code. Always try to write small, testable chunks and build your way up slowly. Try to get your code to compile. ALWAYS. If you can't run your code, you can't test it to figure out what you need to do.
As for the char ** comment you left on lewis's post, here is some reading you may find useful in building up your intuition:
https://www.tutorialspoint.com/what-does-dereferencing-a-pointer-mean-in-c-cplusplus
Happy coding!
The question is to alphabetically sort the given string inputs in ascending order. I wrote the following code for the same. But after printing the entered names the program instead of sorting the strings is giving segmentation fault. I have spent good time over the issue but couldn't figure out anything. Any help would be appreciated.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int x,i,j,length;
printf("Enter the number of names you want to sort.\n");
scanf("%d",&x);
char *names[x],*p,name[50],*t;
printf("Enter the names:\n");
for(i=0;i<x;i++)
{
scanf(" %[^\n]",name);
length = strlen(name);
p = (char *)malloc(length+1);
strcpy(p,name);
names[i] = p;
}
printf("Entered names are:\n\n");
for(i=0;i<x;i++)
{
printf("%s\n",names[i]);
}
printf("\n\nThe sorted names are:\n");
for(i=0;i<x-1;i++)
{
for(j=i+1;j<x;j++)
{
if(strcmp(names[i],names[j])>0)
{
strcpy(t,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],t);
}
}
}
for(i=0;i<x;i++)
{
printf("%s\n",names[i]);
}
return 0;
}
You didn't allocate t so the strcpy(t,names[i]) will segfault.
You can also use strdup()1 to duplicate your strings (instead of malloc() and strcpy()).
And, as your array is of char* elements, you can just swap them directly:
t=names[i];
names[i]=names[j];
names[j]=t;
Regarding your question about pointers, you can consider pointers as uint32_t: they are ”just" values you can assign, like regular integers. It's just their value that is interpreted as an address, rather than a random integer (i.e. its value has a special meaning for the computer, as it is strongly linked to memory).
1: As noted by #WhozCraig, strdup() is not part of the standard library so you'll have to #include the appropriate headers for your platform (it is really widely spread though and hardly a problem).
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
I am new in C programming. Can you please advise, what's wrong with my code? It looks like the if statement is not working, and instead it's jumping and printing the else statement.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char profession;
printf("what is your profession? \n");
scanf(" %s", profession);
if(profession==“QA”)
{
printf(“Go and Test\n“);
}
else
{
printf("Do whatever you want");
}
return 0;
}
First of all, you can't compare strings like that in C. use strcmp or strncmp instead.
Secondly, in your code, profession is a char, and you want to put a string (several chars) in it. It won't work. You can create a char * (pointer on a char) (without forgetting to malloc() it) or a char [] (a char array).
Firstly, strings in C are array of characters, so you have to declare profession as a pointer, pointing to an array of characters. So that statement will look like this char* profession, secondly, you have to use a method called strcmp(char* a, char* b) that accepts two char pointers. This will return 0 if they are equal. I will include the answer, but I assume there are better ways of writing this code.
int main() {
char* profession;
char* compare = "QA";
printf("What is your profession?\n");
scanf(" %s", profession);
if(strcmp(profession, compare) == 0) {
printf("Go and Test\n");
} else {
printf("Do whatever you want");
}
return 0;
}
This question already has answers here:
why this program doesn't give the expected output? [duplicate]
(2 answers)
Closed 7 years ago.
I'm stuck here trying to understand why this assignement can't work in this way in C. What I'm trying to do is substitute all space occurrences with underscore char. (output: Hi_from_Synchronyze)
I saw that the problem comes when I try to do this..
s[n]='_';
the complete code is this one
#include <stdio.h>
#include <stdlib.h>
char *underscore(char *s, int n);
int main()
{
printf("%s", underscore("Hi from Synchronyze", 0));
return 0;
}
char *underscore(char *s, int n)
{
if(s[n]=='\0')
return s;
else {
if(s[n]==' ') {
s[n]='_';
return underscore(s, n+1);
}
else return underscore(s, n+1);
}
}
I'd like to know what's going on behinde and why this happens, not the solution.
Thank you very much in advance
String literals are read-only, so you can't assign to them.
Make a mutable copy of the string first, something like:
char text[] = "Hi from Synchronyze";
printf("%s", underscore(text, 0));
I'm a relatively new programmer and I'm working on a school project. Right now what I'm trying to do is read through a file and get it to check if two characters interact(i.e they appear on the same line).
Right now I haven't too much done and I'm really asking more for ideas rather than code. How would one go about doing something like this? I had a few ideas but none of them actually worked in practise so as of now, this is all I really have done and working:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Characters{
char names[65][50]; //This is the names array
char compnames[65][50]; //This is a duplicate to compare the arrays of characters
int relations;
};
void NameFun();
int main(){
NameFun();
}
void NameFun(){
int i=0, choice;
struct Characters c;
FILE *fp = NULL;
fp = fopen("MisNames.txt", "r");
for(i=0; i<65; i++){
fgets(c.names[i], sizeof(c.names[i]), fp); //Gets each name and stores it as an element of an array
strcpy(c.compnames[i], c.names[i]); //For the duplicate, copying the elements
}
/*The rest of this was for testing purposes and has no real relevance
printf("What number name would you like to know about?\n");
scanf("%d", &choice);
choice = choice--;
printf("\t\t\t%s\n\n", c.names[choice]);
fclose(fp);
}*/