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!
Related
I am writing a program that loops through a text file with two columns. the first values are strings and the second are ints. I am trying to put them in arrays based on their column.
Data example:
stephen 170
shane 150
jake 180
Im trying to do this:
["stephen", "shane", "jake"]
[170,150,180]
For some reason the strcpy function is not working. I am not getting an error message but when I use strcpy and attempt to print the first value of the string array, nothing happens.
#include <stdio.h>
#include <string.h>
int main (void) {
FILE* dict;
char word[50];
int weight;
int weights[50000];
char *words[50000];
dict = fopen("dict.txt", "r");
for (int i = 0; i < 50000; i++) {
fscanf(dict, "%s %d", &word, &weight);
weights[i] = weight;
strcpy(word, words[i]);
}
printf("%s", words[0]);
printf("%d", weights[0]);
return 0;
}
First note that the parameters of strcpy are in the wrong order: the first is the destination and the second is the source, and I guess you want to copy the word string to word[i], so you need to swap the parameters order.
But this won't work either as word[i] points to garbage memory. You'll have to allocate some. You could use for example strdup instead:
words[i] = strdup(word);
Note that it allocates memory on the heap so don't forget to free it once you finished using it.
You have swapped destination and source in your call to strcpy.
Checking man or using a good IDE showing lib function prototypes should help you to avoid that kind of stupid errors for good.
Also, it's mere luck that the program isn't segfaulting as you are reading from words[i] which is an uninitialized array of pointers to chars, you should add a malloc of words[i] before copying to it.
A minimaly fixed (there are still other problems to fix) version of the program could look like below
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
FILE* dict;
char word[50];
int weight;
int weights[50000];
char *words[50000];
dict = fopen("dict.txt", "r");
for (int i = 0; i < 50000; i++) {
fscanf(dict,"%s %d", &word, &weight);
weights[i] = weight;
words[i] = malloc(strlen(word)+1);
strcpy(words[i], word);
}
printf("%s", words[0]);
printf("%d", weights[0]);
return 0;
}
Another option would be to use strdup rather than the current code because it does both malloc and strcpy.
Other obvious problems are that your program will have troubles if any word is longer than 50 characters and it's not trivial to fix using scanf. You could use something like fscanf(dict,"%49s %d", &word, &weight); to avoid overflowing word but if the word is too long that will break the parsing loop. (you will get a line with the beginning of the word and the previous value of weight).
And another issue will happen if your dictionary file has less than 50000 entries.
Let's say that the content of your dictionary file has expected format rather than fixing the code.
I am just starting to work with functions and wish to read an entire array of user input and convert all entries to uppercase. I am still a little confused how to change things in functions and have the changes occur in the array in the main program.
The code I attached is not working:
Any help and/or explanation would be appreciated.
Thank you
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
// function to turn all user input to uppercase
turnUpCase(char *in,200)
{
char *p;
for (p=in; *p='\0'; ++p)
{
*p = toupper(*p);
}
}
int main(void)
{
char input[200];
int i = 0;
printf("Welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
// call to function to turn all input into uppercase
turnUpCase(&input);
return 0;
}
For your turnUpCase function:
1- You are not mentioning any return type.
2- what is 200 ?? write it as retyrn_type turnUpCase(char *p, int size)
in for loop write it as
for (p=in; *p!='\0'; ++p) //to compare with anything use '=='
Name of array is always a pointer. You don't need to mention like turnUpCase(&input). let it go like turnUpCase(input,200)
modify:
turnUpCase(&input); //turnUpCase(input)
turnUpCase(char *in,200) //turnUpCase(char *in)
*p='\0' // *p!='\0'
To make your code work, first you need to change the declaration for turnUpCase() to something like:
void turnUpCase(char *in){}
Since your function does not return a value, it should be declared to be of type void. Next, in the for-loop of the function itself, you have an assignment instead of a comparison. Try this:
for (p = in; *p != '\0'; ++p){}
Finally, when you pass an array to a c function, you are really passing a pointer to the first element of the array, so in your case turnUpCase(input) passes a pointer to the first character of the input string to your function. The way you wrote it, you are passing the address of a pointer to the first character.
Incidentally, I might have written your function like this:
void to_upper(char *str)
{
while(*str) {
*str = toupper(*str);
++str;
}
}
change turnUpCase(&input); to turnUpCase(input); ( an array if passed to a function, "decays" to a pointer to its 1st element, so you don't need to use &) and
also:turnUpCase(char *in,200) to void turnUpCase(char *in) and *p='\0' to *p!='\0'.`
I didn't check if there are the proper libraries for this code to run, but the corrected code seems to be:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
First, we need to declare the method. C needs it inside the header or before the function. Be aware of that this declaration has no body, and ends with ;. After that, we can define the function.
// function to turn all user input to uppercase
void turnUpCase(char *in);
every function needs a return type defined before the definition. Here's the definition and body of the function:
void turnUpCase(char *in) {
char *p;
for (p=in; *p; p++) *p = toupper(*p);
}
Note: As #DavidBowling suggested, this code can be rewritten as (I prefer keeping the original pointer as it was) :
void turnUpCase(char *in) {
char *p = in;
while(*p){
*p = toupper(*p);
p++;
}
}
Both methods check the chars until it reaches a zero char/string end char/null char. Every string in C ends with an \0 (0x00) character, so the function tells that until our string ends, loop the chars and make every char uppercase.
Now the magic begins:
int main(void) {
char input[200];
int i = 0;
printf("Welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
Here, you don't need the addressing & operator, because in C, char arrays are already a pointer to it's contents. But, you might give the first char's address to the method too. So there are two options.
First:
// call to function to turn all input into uppercase
turnUpCase(input);
Second:
// call to function to turn all input into uppercase
turnUpCase(&input[0]);
Then, you can print the result to user.
printf("The uppercase version is: %s", input);
return 0;
}
i compile your code with c++ 4.2.1, and it seems has some compilation error.
when you claim a string, input variable is the pointer of first char in string, so it should be turnUpCase(input) when you call the function.
if want to change variable in function, you need to pass pointer or reference into it. in this case, pass input is just fine.
the reason your code not work may be:
for (p=in; *p='\0'; ++p)
should be:
for (p=in; *p=='\0'; ++p)
I am rather new to the C language right now and I am trying some practice on my own to help me understand how C works. The only other language I know proficiently is Java. Here is my code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * reverse(char word[]);
const char * reverse(char word[]) {
char reverse[sizeof(word)];
int i, j;
for (i = sizeof(word - 1); i <= 0; i--) {
for (j = 0; j > sizeof(word - 1); j++) {
reverse[i] = word[j];
}
}
return reverse;
}
int main() {
char word[100];
printf("Enter a word: ");
scanf("%s", word);
printf("%s backwards is %s\n", word, reverse(word));
return 0;
}
When the user enters a word, the program successfully prints it out when i store it but when i call the reverse function I made it doesnt return anything. It says on my editor the address of the memory stack is being returned instead and not the string of the array I am trying to create the reverse of in my function. Can anyone offer an explanation please :(
sizeof(word) is incorrect. When the word array is passed to a function, it is passed as a pointer to the first char, so you are taking the size of the pointer (presumably 4 or 8, on 32- or 64-bit machines). Confirm by printing out the size. You need to use strlen to get the length of a string.
There are other problems with the code. For instance, you shouldn't need a nested loop to reverse a string. And sizeof(word-1) is even worse than sizeof(word). And a loop that does i-- but compares i<=0 is doomed: i will just keep getting more negative.
There are multiple problems with your reverse function. C is very different from Java. It is a lot simpler and has less features.
Sizes of arrays and strings don't propagate through parameters like you think. Your sizeof will return wrong values.
reverse is an identifier that is used twice (as function name and local variable).
You cannot return variables that are allocated on stack, because this part of stack might be destroyed after the function call returns.
You don't need two nested loops to reverse a string and the logic is also wrong.
What you probably look for is the function strlen that is available in header string.h. It will tell you the length of a string. If you want to solve it your way, you will need to know how to allocate memory for a string (and how to free it).
If you want a function that reverses strings, you can operate directly on the parameter word. It is already allocated outside the reverse function, so it will not vanish.
If you just want to output the string backwards without really reversing it, you can also output char after char from the end of the string to start by iterating from strlen(word) - 1 to 0.
Edit: Changed my reverse() function to avoid pointer arithmetic and to allow reuse of word.
Don't return const values from a function; the return value cannot be assigned to, so const doesn't make sense. Caveat: due to differences between the C and C++ type system, you should return strings as const char * if you want the code to also compile as C++.
Arrays passed as params always "decay" to a pointer.
You can't return a function-local variable, unless you allocate it on the heap using malloc(). So we need to create it in main() and pass it as a param.
Since the args are pointers, with no size info, we need to tell the function the size of the array/string: sizeof won't work.
To be a valid C string, a pointer to or array of char must end with the string termination character \0.
Must put maximum length in scanf format specifier (%99s instead of plain %s — leave one space for the string termination character \0), otherwise vulnerable to buffer overflow.
#include <stdio.h> // size_t, scanf(), printf()
#include <string.h> // strlen()
// 1. // 2. // 3. // 4.
char *reverse(char *word, char *reversed_word, size_t size);
char *reverse(char *word, char *reversed_word, size_t size)
{
size_t index = 0;
reversed_word[size] = '\0'; // 5.
while (size-- > index) {
const char temp = word[index];
reversed_word[index++] = word[size];
reversed_word[size] = temp;
}
return reversed_word;
}
int main() {
char word[100];
size_t size = 0;
printf("Enter a word: ");
scanf("%99s", word); // 6.
size = strlen(word);
printf("%s backwards is %s\n", word, reverse(word, word, size));
return 0;
}
For my assignment, I have to read in a text file with a varying amount of lines. They follow the following format:
AACTGGTGCAGATACTGTTGA
3
AACTGGTGCAGATACTGCAGA
CAGTTTAGAG
CATCATCATCATCATCATCAT
The first line is the original line I will testing the following ones against, with the second line giving the number of remaining lines.
I'm having trouble trying to save these to a struct, and can't even get the first line to save. I tried using the void function with an array and it seems to work, but can't seem to transfer it over to structs.
Here's my code so far:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH 25
struct dna {
char code[LENGTH];
};
int main(){
char filename[] = "input1.txt";
FILE *input = fopen("input1.txt","r");
char firstDna[LENGTH]="";
struct dna first;
struct dna first.code[]= "";
makeArray(input,first);
// printf("%s",filename);
system("pause");
return 0;
}
void makeArray(FILE *input,struct dna first){
int i=-1;
//nested for loops to initialze array
//from file
while(i != '\n'){
fscanf(input,"%c",first[i].code);
printf("%c", first[i].code);
i++;
}//closing file
fclose(input);
}
Since this is for a class assignment, I want to preface this by saying that a good way to tackle these types of assignments is to break it up into tasks, then implement them one by one and finally connect them. In this case the tasks might be something like:
parse the first line into a (struct containing a) char array.
parse the number into an int variable
parse each remaining line in the file like you did with the first line
test the first line against the other lines in the file (except the number)
You also mentioned in a comment that the struct is for extra credit. For that reason, I'd recommend implementing it using just a char array first, then refactoring it into a struct once you have the basic version working. That way you have something to fall back on just in case. This way of developing might seem unnecessary at this point, but for larger more complicated projects it becomes a lot more important, so it's a really good habit to get into as early as possible.
Now, let's look at the code. I'm not going to give you the program here, but I'm going to identify the issues I see in it.
Let's start with the main method:
char filename[] = "input1.txt";
FILE *input = fopen("input1.txt","r");
This opens the file you're reading from. You're opening it correctly, but the first line is in this case unnecessary, since you never actually use the filename variable anywhere.
You also correctly close the file at the end of the makeArray function with the line:
fclose(input);
Which works. It would, however, probably be better style if you put this in the main method after calling the makeArray function. It's always a good idea to open and close files in the same function if possible, since this means you will always know you didn't forget to close the file without having to look through your entire program. Again, not really an issue in a small project, but a good habit to get into. Another solution would be to put the fopen and fclose functions in the makeArray function, so main doesn't have to know about them, then just send the char array containing the filepath to makeArray instead of the FILE*.
The next issue I see is with how you are passing the parameters to the makeArray function. To start off, instead of having a separate function, try putting everything in the main method. Using functions is good practice, but do this just to get something working.
Once that's done, something you need to be aware of is that if you're passing or returning arrays or pointers to/from functions, you will need to look up the malloc and free functions, which you may not have covered yet. This can be one of the more complex parts of C, so you might want to save this for last.
Some other things. I won't go into detail about these but try to get the concepts and not just copy paste:
struct dna first.code[]= ""; should probably be first.code[0] = \0;. \0 is used in C to terminate strings, so this will make the string empty.
Passing %c to fscanf reads a single character (you can also use fgetc for this). In this case, it will probably be easier using %s, which will return a word as a string.
Assuming you do use %s, which you probably should, you will need to call it twice before the loop - once to get the first DNA sequence and another time to get the number of other DNA sequences (the number of iterations).
Each iteration of the loop will then test the original DNA sequence against the next DNA sequence in the file.
I hope that helps!
sample to fix
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH 25
struct dna {
char code[LENGTH];
};
struct dna *makeArray(FILE *input, int *n);//n : output, number of elements
int main(void){
char filename[] = "input1.txt";
FILE *input = fopen(filename,"r");
struct dna first = { "" };
fscanf(input, "%24s", first.code);//read first line
printf("1st : %s\n", first.code);
int i, size;
struct dna *data = makeArray(input, &size);//this does close file
for(i = 0; i < size; ++i){
printf("%3d : %s\n", i+1, data[i].code);
}
free(data);//release data
system("pause");
return 0;
}
struct dna *makeArray(FILE *input, int *n){//n : output, number of elements
int i;
fscanf(input, "%d", n);//read "number of remaining lines"
struct dna *arr = calloc(*n, sizeof(struct dna));//like as struct dna arr[n] = {{0}};
for(i = 0; i < *n; ++i){
fscanf(input, "%24s", arr[i].code);
}
fclose(input);
return arr;
}
a simple fix might be :
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH 25
struct dna {
char code[LENGTH];
};
void makeArray(FILE *input,struct dna *first){
int i=0;
fscanf(input,"%c",&first->code[i]);
printf("%c",first->code[i]);
while(first->code[i] != '\n' && i < LENGTH){
i++;
fscanf(input,"%c",&first->code[i]);
printf("%c",first->code[i]);
}
}
int main() {
struct dna first;
char filename[] = "input1.txt";
FILE *input = fopen(filename,"r");
makeArray(input,&first);
fclose(input);
printf("%s",first.code);
return 0;
}
PS: i tried to not change your original code
in order to change the code[Length] in the makeArray function you will have to pass it's adresse this is why i call mkaeArray function this way : makeArray(input,&first);.
Below is my code snippet
struct encode
{
char code[MAX];
}a[10];
int main()
{
char x[]={'3','0','2','5','9','3','1'};
for(i=0;i<1;i++)
{
printf("%c",x[i]);
//This will printout like 3025931 now I want this to be stored in structure.
}
strcpy(a[0].code,x);
// or
a[0].code=x;//neither works
display();
}
void display()
{
printf("%c",a[0].code);
}
I want the output to be like:3025931.
Which I am not getting due to incompatible assign type. Please tell me where am i going wrong.
I see two problems here. The first is that the source of the strcpy is a where it probably should be x.
The second is that x is not null-terminated. Strings in C are null-terminated character arrays.
I would change the two lines:
char x[] = {'3','0','2','5','9','3','1'};
strcpy(a[0].code, a);
to:
char x[] = {'3','0','2','5','9','3','1', '\0'};
strcpy(a[0].code, x);
Here's a complete program that gives you what you want (it actually prints out the number twice, once in your inner loop character by character and once with the printf so that you can see they're the same):
#include <stdio.h>
#include <string.h>
#define MAX 100
struct encode {
char code[MAX];
} a[10];
int main() {
int i, j;
char x[] = {'3','0','2','5','9','3','1','\0'};
for(i = 0; i < 1; i++) {
for(j = 0; j < 7; j++) {
printf("%c", x[j]);
}
printf("\n");
strcpy(a[0].code, x);
}
printf("%s\n",a[0].code);
return 0;
}
Update based on comment:
I am sorry. I am new to C. My apologies for not pasting the code snippet correctly in the beginning: "printf("%c",a[0].code);" doesn't display "3025931".
No, it won't. That's because a[0].code is a character array (string in this case) and you should be using "%s", not "%c". Changing the format specifier in the printf should fix that particular issue.
Here,
strcpy(a[0].code, a);
did you mean
strcpy(a[0].code, x);
...?
Also, x needs to be null terminated, or you need to replace strcpy with strncpy or memcpy and pass in a length.
This line doesn't make much sense:
strcpy(a[0].code, a);
Perhaps you want this:
memcpy(a[0].code, x, sizeof x);
a[0].code[sizeof x] = '\0';
(The second line is necessary to nul-terminate code, making it a proper C string).
A lot of things are wrong in your program. The most offending line is this:
strcpy(a[0].code, a);
but there are other oddities as well, e.g.
display is never called
a is only assigned (kind of), but never read (except in display, which is never called)
the i loop makes no sense
Basically, this program looks like copy-pasted by someone who has no clue.