Task is to add * after every * in string:
Input:*fsd*fds*fds*f
Output: **fsd**fds**fds**f
I found this and i am trying to replace every * with **
But it wont work.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <string.h>
int main() {
char x[256];
scanf("%s", &x);
for (char* p = x; p = strchr(p, '*'); ++p) {
*p = '*';
}
printf("%s", x);
system("pause");
return 0;
}
it only works when i use one char in this line
*p = '*';
but when i use more it does not work.
so *p = '**'; does not work.
Thanks for any help or hint.
It's easier to write the code if you just read one character at a time like this:
#include <stdio.h>
int main() {
while (1) {
int input = fgetc(stdin);
if (input == EOF) { break; }
if (input == '*') { fputc('*', stdout); }
fputc(input, stdout);
}
}
Also, since we are not dealing with memory allocations, arrays, or strings here, it is a lot easier to write safe code that will not suffer from buffer overflow bugs.
Note: Recent versions of the C standard put return 0; implicitly at the end of your main function so you don't have to write it yourself.
As I mentioned in the comments, when you replacing * with ** you are writing two characters in place of one, so it replaces the next character after *. One otherway would be to take another empty array and copy elements from input string, when you find * you can insert two ** Following snippet shows one potential solution.
#include<stdio.h>
#include <string.h>
int main() {
char x[256],y[256];
unsigned index = 0;
scanf("%s", x);
for (unsigned i = 0; i < strlen(x); i++) {
y[index++] = x[i];
if(x[i] == '*')
y[index++] = '*';
}
y[index] = '\0';
printf("%s", y);
system("pause");
return 0;
}
Related
I'm trying to write a program that gets a string, and a number, and calculates the length of it and shifting all the elents right.
I have 2 errors:
1.assignment makes pointer from integer without a cast.
2.assignment makes integer from pointer without a cast.
#include <stdio.h>
#include <string.h>
#define N 10
int myStrlen(char*);
void shiftRight(char*, int);
int main() {
char str[N] = {0};
int num = 0;
int len;
/* input of the string */
scanf("%s",str);
scanf("%d",&num);
len=myStrlen(str);
if(num>=0) {
shiftRight(str, num);
printf("%s\n",str);
}
else
{
printf("%s\n", str);
}
return 0;
}
int myStrlen(char*str)
{
int my_len=0;
while (str[my_len] != '\0')
{
my_len++;
}
return my_len;
}
void shiftRight(char* str, int num)
{
int i;
char* j;
int count;
j=(str[N-1]);
for(count=0;count<num;count++)
{
for(i=N-1;i>0;--i)
{
str[i]=str[i-1];
}
str[0]=j;
}
}
Your answers are welcome,anf if you anything wrong with this code,please mention it.
As your compiler will have told you, pointer from integer without a cast is at
j=(str[N-1]);
And integer from pointer is at
str[0]=j;
You should have declared j as char j;
But now when i run it, and typing lets say ball as a string and 1 to
be a number, i get nothing from the program instead of getting "lbal"
You have all the correct elements but that's not enough. Writing a program is telling a story, you need to set the scene, describe what happens along the way and conclude your narrative. A story with elements out of order is nonsense, as is a program.
Specific issues with your code: you're saving of the last character (to restore it to the beginning of the string) is in the wrong place; you're using the allocation of the string when you should be using it's length (and conveniently, you have a function for that!); this is really more of a rotation than a shift; use the most descriptive variable names you can, not the shortest you can get away with; pick one indentation style and stick with it -- it can change between programs you write but shouldn't change within an individual program.
Below is a rework of your code addressing some of the issues above:
#include <stdio.h>
#define STRING_SIZE 10
int myStrlen(char *string)
{
int length = 0;
while (string[length] != '\0')
{
length++;
}
return length;
}
void rotateRight(char *string, int number)
{
int length = myStrlen(string);
for (int count = 0; count < number; count++)
{
char j = string[length - 1];
for (int i = length - 1; i > 0; i--)
{
string[i] = string[i - 1];
}
string[0] = j;
}
}
int main()
{
char string[STRING_SIZE] = {0};
int number = 0;
/* input of the string */
scanf("%s", string);
scanf("%d", &number);
if (number > 0)
{
rotateRight(string, number);
printf("%s\n", string);
}
else
{
printf("%s\n", string);
}
return 0;
}
OUTPUT
% ./a.out
elephant
3
anteleph
%
I have written a code trying to split a long string to get simpler strings so that i could sort them out... When i break from the nested loop, does it break up to the first loop entirely??
My input is "&$(, My,na$me(is"
the output that i wanted is "My na me is"
How can i solve this??
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char splitter[100];
char mystring[1000];
char newstring[1000][1000];
int i,j,z,k=0;
scanf("%s", splitter);
scanf("%s", mystring);
for (i=0; i<1000; i++){
for (j=k; j<1000; j++){
for (z=0; z<100; z++){
if (mystring[j]==splitter[z]){
k++;
break;
}
else
{
newstring[i][j]=mystring[j];
}
}
if (mystring[j]==splitter[z])
break;
}
}
for (i=0; i<10; i++){
printf("%s ", newstring[i]);
}
return 0;
}
First; C is not Python, you can't just use indent to denote blocks, you must use braces, i.e. { and }.
Second, no a break only breaks the closest-most loop its in, there's no way to break out of more than one level.
Third, you're looping over the strings as if they're always 100 characters long which they won't always be (for instance in your example they're not). This is wrong, you should use strlen() to figure out how long they are.
Fourth, you should check the return values of your scanf() calls, since it can fail.
Fifth, newstring is declared as an array of arrays, i.e. a gigantic one-megabyte 2D "square" of characters, which is clearly not how you're using it.
#include <stdio.h>
#include <string.h>
int main(){
char splitter[100];
char mystring[1000];
char *tokens[500];
char *token;
int i=0;
scanf("%99[^\n]%*c", splitter);
scanf("%999[^\n]", mystring);
token = strtok(mystring, splitter);
while(token){
if(i)
putchar(' ');
printf("%s", token);
tokens[i++] = token;
token = strtok(NULL, splitter);
}
putchar('\n');
return 0;
}
Though there are many mistakes in your code and I am unable to find out why are you doing those mistakes.For example I dint get why are you scaning two arrays and why are you using a two-D array.Another thing I would like to tell you is that scanf doesnt work when there is spaces in the string.According to your problem here is very simple solution.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(){
char splitter[100];
char mystring[1000];
char newstring[1000][1000];
int i,j,z,k=0;
gets(splitter);
for(i=0;i<strlen(splitter);++i){
if(((splitter[i])>=65 &&(splitter[i]<=90)) || ((splitter[i]>=97)&&(splitter[i] <=122)))
mystring[k++]=splitter[i];
else
mystring[k++]=' ';
}
printf("%s\n",mystring);
//scanf("%s", mystring);
return 0;
}
Check the below code:
int main()
{
int i=0,j=0,t,f=0;
char s[20];
char b[20];
printf("Enter the string\n");
scanf("%s",&s);
while(s[i] != '\0')
{
t = s[i];
if((t>=65 && t<=90) || (t>= 97 && t<=122))
{
b[j++] = s[i];
f = 1;
}
else
{
if(f)
b[j++] = ' ';
}
i++;
}
b[j] = '\0';
printf("%s\n",b);
return 0;
}
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//function prototypes
void checkAnswer(char *, char[]);
int main(void) {
char *strGame[5] = { "ADELANGUAGEFERVZOPIBMOU", "ZBPOINTERSKLMLOOPMNOCOT",
"PODSTRINGGDIWHIEEICERLS", "YVCPROGRAMMERWQKNULTHMD",
"UKUNIXFIMWXIZEQZINPUTEX" };
char answer[80] = { 0 };
int displayed = 0;
int x;
int startTime = 0;
system("clear");
printf("\n\n\tWord Find\n\n");
startTime = time(NULL);
for (x = 0; x < 5; x++) {
/* DISPLAY TEXT FOR A FEW SECONDS */
while (startTime + 3 > time(NULL)) {
if (displayed == 0) {
printf("\nFind a word in: \n\n");
printf("%s\n\n", strGame[x]);
displayed = 1;
}
}
system("clear");
printf("\nEnter word found: ");
fgets(answer, 80, stdin);
checkAnswer(strGame[x], answer);
displayed = 0;
startTime = time(NULL);
}
}
void checkAnswer(char *string1, char string2[]) {
int x;
for (x = 0; x <= strlen(string2); x++)
string2[x] = toupper(string2[x]);
if (strstr(string1, string2) != 0)
printf("\nGreat job!\n");
else
printf("\nSorry, word not found!\n");
}
When I run the code, it doesn't register my input correctly. It tells me that the word wasn't found. I used toupper to make my input the same as my strings and strstr to compare my input with the strings. I took this from a basic C programming book. It used gets. I know that you shouldn't use gets so I changed it to fgets. Is this where the problem is? Any suggestions?
You can avoid the issue with the \n (newline) mentioned by BLUEPIXY -- namely, that gets() removes it but fgets() does not -- by reversing the terms in your call to checkAnswer():
checkAnswer(answer, strGame[x]);
checkAnswer() then uses the same order with strstr(). If you search for "foobar" in "foobar\n", strstr() will return a pointer. But if you search for "foobar\n" in "foobar", it won't.
The newline is there because the user hits Enter. So another way around this would be to add a \n to the end of all your strGame[] strings. Or, you could remove any newline in the answer with:
void truncateAtNewline (char *str) {
char *p = strchr(str, '\n');
if (p) *p = '\0';
}
The problem is that fgets() will leave the newline at the end of the string. When you type the word, then you press Enter and fgets() interprets that as input.
So, a way to bypass this is to eat the newline by doing this:
fgets(answer, 80, stdin);
// go to the last position where the
// newline is placed and replace it
// with the null terminator
answer[strlen(answer)-1] = '\0';
Also here:
for (x = 0; x <= strlen(string2); x++)
string2[x] = toupper(string2[x]);
the <= is not needed, since you start from 0, thus change it to this:
for (x = 0; x < strlen(string2); x++)
string2[x] = toupper(string2[x]);
How I found your problem? I used printf to output the strings before comparing them.
void checkAnswer(char *string1, char string2[]) {
int x;
for (x = 0; x < strlen(string2); x++)
string2[x] = toupper(string2[x]);
printf("|%s|\n", string1);
printf("|%s|\n", string2);
if (strstr(string1, string2) != 0)
printf("\nGreat job!\n");
else
printf("\nSorry, word not found!\n");
}
Output before my fix:
|ADELANGUAGEFERVZOPIBMOU|
|ADEL
|
Output after the fix:
|ADELANGUAGEFERVZOPIBMOU|
|ADEL|
Or you can use a function to trim newlines and spaces. I have some methods here.
Consider also not using system().
Moreover, always add a return 0; line of code before your main() ends.
I am writing C program that reads input from the standard input a line of characters.Then output the line of characters in reverse order.
it doesn't print reversed array, instead it prints the regular array.
Can anyone help me?
What am I doing wrong?
main()
{
int count;
int MAX_SIZE = 20;
char c;
char arr[MAX_SIZE];
char revArr[MAX_SIZE];
while(c != EOF)
{
count = 0;
c = getchar();
arr[count++] = c;
getReverse(revArr, arr);
printf("%s", revArr);
if (c == '\n')
{
printf("\n");
count = 0;
}
}
}
void getReverse(char dest[], char src[])
{
int i, j, n = sizeof(src);
for (i = n - 1, j = 0; i >= 0; i--)
{
j = 0;
dest[j] = src[i];
j++;
}
}
You have quite a few problems in there. The first is that there is no prototype in scope for getReverse() when you use it in main(). You should either provide a prototype or just move getReverse() to above main() so that main() knows about it.
The second is the fact that you're trying to reverse the string after every character being entered, and that your input method is not quite right (it checks an indeterminate c before ever getting a character). It would be better as something like this:
count = 0;
c = getchar();
while (c != EOF) {
arr[count++] = c;
c = getchar();
}
arr[count] = '\0';
That will get you a proper C string albeit one with a newline on the end, and even possibly a multi-line string, which doesn't match your specs ("reads input from the standard input a line of characters"). If you want a newline or file-end to terminate input, you can use this instead:
count = 0;
c = getchar();
while ((c != '\n') && (c != EOF)) {
arr[count++] = c;
c = getchar();
}
arr[count] = '\0';
And, on top of that, c should actually be an int, not a char, because it has to be able to store every possible character plus the EOF marker.
Your getReverse() function also has problems, mainly due to the fact it's not putting an end-string marker at the end of the array but also because it uses the wrong size (sizeof rather than strlen) and because it appears to re-initialise j every time through the loop. In any case, it can be greatly simplified:
void getReverse (char *dest, char *src) {
int i = strlen(src) - 1, j = 0;
while (i >= 0) {
dest[j] = src[i];
j++;
i--;
}
dest[j] = '\0';
}
or, once you're a proficient coder:
void getReverse (char *dest, char *src) {
int i = strlen(src) - 1, j = 0;
while (i >= 0)
dest[j++] = src[i--];
dest[j] = '\0';
}
If you need a main program which gives you reversed characters for each line, you can do that with something like this:
int main (void) {
int count;
int MAX_SIZE = 20;
int c;
char arr[MAX_SIZE];
char revArr[MAX_SIZE];
c = getchar();
count = 0;
while(c != EOF) {
if (c != '\n') {
arr[count++] = c;
c = getchar();
continue;
}
arr[count] = '\0';
getReverse(revArr, arr);
printf("'%s' => '%s'\n", arr, revArr);
count = 0;
c = getchar();
}
return 0;
}
which, on a sample run, shows:
pax> ./testprog
hello
'hello' => 'olleh'
goodbye
'goodbye' => 'eybdoog'
a man a plan a canal panama
'a man a plan a canal panama' => 'amanap lanac a nalp a nam a'
Your 'count' variable goes to 0 every time the while loop runs.
Count is initialised to 0 everytime the loop is entered
you are sending the array with each character for reversal which is not a very bright thing to do but won't create problems. Rather, first store all the characters in the array and send it once to the getreverse function after the array is complete.
sizeof(src) will not give the number of characters. How about you send i after the loop was terminated in main as a parameter too. Ofcourse there are many ways and various function but since it seems like you are in the initial stages, you can try up strlen and other such functions.
you have initialised j to 0 in the for loop but again, specifying it INSIDE the loop will initialise the value everytime its run from the top hence j ends up not incrmenting. So remore the j=0 and i=0 from INSIDE the loop since you only need to get it initialised once.
check this out
#include <stdio.h>
#include <ctype.h>
void getReverse(char dest[], char src[], int count);
int main()
{
// *always* initialize variables
int count = 0;
const int MaxLen = 20; // max length string, leave upper case names for MACROS
const int MaxSize = MaxLen + 1; // add one for ending \0
int c = '\0';
char arr[MaxSize] = {0};
char revArr[MaxSize] = {0};
// first collect characters to be reversed
// note that input is buffered so user could enter more than MAX_SIZE
do
{
c = fgetc(stdin);
if ( c != EOF && (isalpha(c) || isdigit(c))) // only consider "proper" characters
{
arr[count++] = (char)c;
}
}
while(c != EOF && c != '\n' && count < MaxLen); // EOF or Newline or MaxLen
getReverse( revArr, arr, count );
printf("%s\n", revArr);
return 0;
}
void getReverse(char dest[], char src[], int count)
{
int i = count - 1;
int j = 0;
while ( i > -1 )
{
dest[j++] = src[i--];
}
}
Dealing with strings is a rich source of bugs in C, because even simple operations like copying and modifying require thinking about issues of allocation and storage. This problem though can be simplified considerably by thinking of the input and output not as strings but as streams of characters, and relying on recursion and local storage to handle all allocation.
The following is a complete program that will read one line of standard input and print its reverse to standard output, with the length of the input limited only by the growth of the stack:
int florb (int c) { return c == '\n' ? c : putchar(florb(getchar())), c; }
main() { florb('-'); }
..or check this
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
char *my_rev(const char *source);
int main(void)
{
char *stringA;
stringA = malloc(MAX); /* memory allocation for 100 characters */
if(stringA == NULL) /* if malloc returns NULL error msg is printed and program exits */
{
fprintf(stdout, "Out of memory error\n");
exit(1);
}
else
{
fprintf(stdout, "Type a string:\n");
fgets(stringA, MAX, stdin);
my_rev(stringA);
}
return 0;
}
char *my_rev(const char *source) /* const makes sure that function does not modify the value pointed to by source pointer */
{
int len = 0; /* first function calculates the length of the string */
while(*source != '\n') /* fgets preserves terminating newline, that's why \n is used instead of \0 */
{
len++;
*source++;
}
len--; /* length calculation includes newline, so length is subtracted by one */
*source--; /* pointer moved to point to last character instead of \n */
int b;
for(b = len; b >= 0; b--) /* for loop prints string in reverse order */
{
fprintf(stdout, "%c", *source);
len--;
*source--;
}
return;
}
Output looks like this:
Type a string:
writing about C programming
gnimmargorp C tuoba gnitirw
So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!