my programming teacher have sent some exercises for practice, and this one I've no clue for a way to solve it.
In his example, he asks: write a program that gets a phrase or a word, turn it backwards and write it weirdly.
I'm trying to use the phrase "ABCDE" write it backwards and then, start writing the phrase from the middle.
In the end, he wants something like: CBAED
All I have so far, is the phrase/word backwards, like: EDCBA
Well, this is my code so far:
#include <stdio.h>
void inverter();
int main(){
printf("sentence to revert: ");
inverter();
return 0;
}
void inverter(){
char letra;
scanf("%c",&letra);
if( letra != '\n'){
inverter();
printf("%c",letra);
}
}
As you guys have seen, I'm a newbie in C (and in English) so, if any of you could give me a way to proceed, I would appreciate it a lot.
Edit: I believe I was not happy on the phrase I've selected as an exemple, so I've changed it.
Without telling you exactly the code to write, because you are asking for help with academic work, you can try this:
Read in a line of text.
Using the length of the line (scanf returns an int with the number of characters read if I'm not mistaken), loop through it backwards, printing each character at a time.
Something to try would be like this:
//This is pseudocode. Do not copy/paste
for(int i = length of line; i > 0; i--) {
print out line[i];
}
Then divide the length by 2 and run two loops in reverse, one starting in the middle:
//This is Psuedocode. Do not copy/paste
for(int i = middle of line; i > 0; i--) {
print out line[i];
}
And then another starting at the end:
//This is Pseudocode. Do not copy/paste
for(int i = length of line; i > middle of line; i--) {
print out line[i];
}
????
Profit
Obviously, you will have to tweak a few things here and there. For example, i = length of line will cause a runtime error, but you're here to learn and I believe in learning by doing.
Related
I'm writing a program that scan words from a text file
how can I scan only the word that starts with space or number and end with a space
Without taking ',.()\t\n to my string
I know i can use the function scanf but didn't quite get how to use it that way
Another small question
I'm looking to count how many lines there are in my text
so I guess I should look for a "\n" sign to increase my count right?
First of all when you ask a question you need to follow some rules, here is a like for how to ask questions in stack overflow:
How to ask from the Stack Overflow Help Center
If I was doing this task I would read it char by char using a 'while loop' ends at EOF and inside of it a 'if' checks if you should add this char to your string and adding it using realloc.
For your second question put another 'if' before the first one that checks if the char == to '\n' and if so ++ to a int that count number of lines.
At the end it should look like this:
int *input = malloc(sizeof(int));
int linesLength = 0;
int now;
int lines = 0;
whlie ((now = getc(file)) != EOF){
if (now == '\n') {
lines += 1;
}
if (/* what chars you want out */){
/* add your char using realloc */
linesLength += 1;
}
}
Btw this is the exact same task I need to do till the 18 to this month and your name looks familiar, the point is, this is not a site for homework, pay attention for this next time.
I am new to programming in C and still trying to learn all of the useful functions it provides in its libraries. In particular I'm trying to wrap my head around how to use getchar() for more than one character in a certain situation. I want to be able to have input from the console be something like:
11 2 34 100
I want to be able to distinguish between these entries(delimiter space I guess?), and add these numbers up. This is an assignment, so I was wondering if someone could give me a hint or point me in the right direction on how to go further with this. I would certainly appreciate it. This is what I have at the moment. Also, we're not supposed to make use of arrays here. This really threw me because I don't see any other way. Again any help or pointers in the right direction would go a long way!
int main()
{
int count = 0;
char input;
int wordCount = 0;
int numEntered = 0;
input = getchar();
while(input != '\n')
{
if(input != ' ')
{
count++;
}
input = getchar();
}
printf("Number of characters included in numbers %d\n", count);
return 0;
}
You can store two integers, one that is the running total, and one that is the current number.
If you encounter a digit that is not a space, multiply the current number by 10 and then add that digit to the current number.
If you encounter a space, add the current number to the running total, then reset the current number to 0.
I know it's a little unorthodox and will probably cost me some downvotes, but since it's due in 1 hour and I have no idea where to begin I thought I'd ask you guys.
Basically I'm presented with a string that contains placeholders in + form, for example:
1+2+5
I have to create a function to print out all the possibilities of placing different combinations of any given series of digits. I.e. for the series:
[9,8,6] // string array
The output will be
16265
16285
16295
18265
18285
18295
19265
19285
19295
So for each input I get (number of digits)^(number of placeholders) lines of output.
Digits are 0-9 and the maximum form of the digits string is [0,1,2,3,4,5,6,7,8,9].
The original string can have many placeholders (as you'd expect the output can get VERY lengthly).
I have to do it in C, preferably with no recursion. Again I really appreciate any help, couldn't be more thankful right now.
If you can offer an idea, a simplified way to look at solving this, even in a different language or recursively, it'd still be ok, I could use a general concept and move on from there.
It prints them in different order, but it does not matter. and it's not recursive.
#include <stdlib.h>
#include <stdio.h>
int // 0 if no more.
get_string(char* s, const char* spare_chr, int spare_cnt, int comb_num){
for (; *s; s++){
if (*s != '+') continue;
*s = spare_chr[comb_num % spare_cnt];
comb_num /= spare_cnt;
};
return !comb_num;
};
int main(){
const char* spare_str = "986";
int num = 0;
while (1){
char str[] = "1+2+5";
if (!get_string(str, spare_str, strlen(spare_str), num++))
break; // done
printf("str num %2d: %s\n", num, str);
};
return 0;
};
In order to do the actual replacement, you can use strchr to find the first occurrence of a character and return a char * pointer to it. You can then simply change that pointer's value and bam, you've done a character replacement.
Because strchr searches for the first occurrence (before a null terminator), you can use it repeatedly for every value you want to replace.
The loop's a little trickier, but let's see what you make of this.
I've been trying to write a function in C that detects palindromes. The program currently looks like the following:
#include <stdio.h>
#include <string.h>
int main()
{
char palindrome[24]; int palength; int halflength;
gets(palindrome);
palength = strlen(palindrome);
halflength = palength / 2;
printf("That string is %u characters long.\r\n", palength);
printf("Half of that is %u.\r\n", halflength);
return 0;
}
Right now it detects the length of a string, and also shows what half of that is. This is just to make sure it is working how I think it should be. What the rest of the function should do (if possible) is take the integer from "halflength" and use that to take that amount of characters off of the beginning and end of the string and store those in separate strings. From there I'd be able to compare the characters in those, and be able return true or false if the string is indeed a palindrome.
TL;DR - Is it possible take a certain amount of characters (in this case the integer "halflength") off the front and end of a string and store them in separate variables. Read above for more information on what I'm trying to do.
P.S. - I know not to use gets(), but didn't feel like writing a function to truncate \n off of fgets().
int len = strlen(palindrome) - 1; // assuming no \n
int half = len << 1;
for (int i=0; i<=half; ++i)
if(palindrome[i] != palindrome[len-i])
return false;
return true;
What if you do something like this,
char *str1="lol",*str2;
str2=strrev(str1);
//if both are same then it actually is a palindrome ; )
Found out I was approaching the problem wrong. How I should be doing this is iterating over the characters using a pointer both backwards and forwards. Although if you'd still like to answer the original question it could still be useful at some point.
I'm trying to create a function to read Morse code from one file, convert it to English text, print the converted text to the terminal, and write it to an output file. Here's a rough start...
#define TOTAL_MORSE 91
#define MORSE_LEN 6
void
morse_to_english(FILE* inputFile, FILE* outputFile, char morseStrings[TOTAL_MORSE][MORSE_LEN])
{ int i = 0, compare = 0;
char convert[MORSE_LEN] = {'\0'}, *buffer = '\0';
//read in a line of morse string from file
// fgets(buffer, //then what?
while(((convert[i] = fgetc(inputFile)) != ' ') && (i < (MORSE_LEN - 1)))
{ i++;
}
if (convert[i + 1] == ' ')
convert[i + 1] = '\0';
//compare read-in string w/morseStrings
for (i = 48, compare = strcmp(convert, morseStrings[i]); //48 is '0'
i < (TOTAL_MORSE - 1) && compare != 0;
i++)
{ compare = strcmp(convert, morseStrings[i]);
}
printf("%c", (char)i);
}
I have initialized morseStrings to the morse code.
That's my function right now. It does not work, and I'm not really sure what approach to take.
My original algorithm plan was something like this:
1. Scan Morse code in from file, character by character, until a space is reached
1.1 save to a temporary buffer (convert)
2. loop while i < 91 && compare != 0
compare = strcmp(convert, morseString[i])
3. if (test ==0) print ("%c", i);
4. loop through this until eof
but.. I can't seem to think of a good way to test if the next char in the file is a space. So this has made it very difficult for me.
I got pretty frustrated and googled for ideas, and found a suggestion to use this algorithm
Read a line
Loop
-strchr() for a SPACE or EOL
-copy characters before the space to another string
-Use strcmp() and loop to find the letter
-Test the next character for SPACE.
-If so, output another space
-Skip to next morse character
List item
Endloop
But, this loops is kind of confusing. I would use fgets() (I think), but I don't know what to put in the length argument.
Anyways, I'm tired and frustrated. I would appreciate any help or insight for this problem. I can provide more code if necessary.
Your original plan looks fine. You're off by 1 when you check for the ' ' in the buffer, though. It's at convert[i], not convert[i + 1]. The i++ inside the loop doesn't happen when a space is detected.
I wouldn't use strchr(), to complicated.
Loop through the Inputfile reading a line
tokenize line with [strtok][1]
loop through tokens and save(best append) the single Letters to a Buffer
close looops and print
a bit of pseudocode for u
while(there is a next line){
tokens = strtok(line);
int i = 0;
while(tokens hasnext){
save to buffer}}
If you are concerned about the CPU time you can write a lookup table to find the values, something as a switch like this:
case '.-': code = "A"; break;
case '-...': code = "B"; break;
case '-.-.': code = "C"; break;
After you split the morse code by the spaces and send the diferent . and - combinations to the switch to get the original character.
I hope this help.
Best regards.