I have a simple program in C. The program has the following parameters: -It will
ID: 3858981 • Letter: I
Question
I have a simple program in C.
The program has the following parameters:
-It will read a single line of text from standard input.
-It will print "R=" followed by that line backwards and then exit.
eg:
./linex
123456
would output
R=654321
Notes:
i) your program must not leak memory or perform any invalid memory accesses.
ii) your program should not use more memory than it needs.
iii) do not call fgets or getline
Without using fgets, scanf is the only option. With this I need to be able to read a single line and make sure that the memory used is not larger than needed. How would I use scanf to creae dynamic memory and also read the white spaces in which scanf finishes. Thankyou for your help.
Thus far I have the following code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * strrev(char *str) {
long i = strlen(str) - 1, j = 0;
char ch;
while(i > j)
{
ch = str[i];
str[i] = str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main(int argc, const char * argv[]) {
long a = 10;
char name[a];
scanf("%[^ ]s",name);
a = strlen(name);
printf("%s ", name);
printf("%s ", strrev(name));
}
Explanation / Answer
Solution:-
The below given C program will reverse the string entered in the standard input. As per requirement there is no call to fgets or getline. This is a simple program and input is read only using the scanf. NO other inbuilt function is used. The output is given below the program.
The code starts here -
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
int main()
{
char mystring[50];
int len, i;
//print a string about the program
printf("C Program to reverse a string ");
printf("Enter a string: ");
//get the input string from the user
scanf("%s", mystring);
//find the length of the string using strlen()
len = strlen(mystring);
//loop through the string and print it backwards
printf("The reverse string is R=");
for(i=len-1; i>=0; i--){
printf("%c", mystring[i]);
}
return 0;
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Output -
C Program to reverse a string
Enter a string: 123456
The reverse string is
R=654321
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.