views:

274

answers:

6

It's a part of my final project; I don't understand C well. I have just this, and I don't know anything more.

Please don't delete my question. I was looking for the answer a long time. I guess I'm not the only student with this problem. And why is there no option to send a private message or see a user's e-mail?

wow, guys...actually i first time see so friendly forum, it's gonna be my favourite one) i didn't imagine that anybody can care about all these 'homework policies'.I can say just, i'm not really lazy student, it's just not my thing. I'm doing computing course, i didn't have a choice to choose my profession. And i'm working hard every day, there are a lot of 'computer's genius' in my class, they can write a simple program just in class for fun for 5 mins. But i need 1 day for doing the same thing. u cant imagine how much else i have to do. can someone just DON'T WORRY about my real knowledgements in computing and give me his e-mail. i'm already ashamed of the moralistic...

enter code here 
#include <stdio.h>
#define SIZE 1000

void read_str();


main() {

char search_key;
char *ptr1;

char s1[SIZE];

    ptr1 = s1;


printf("Enter your string:\n");
            read_str();

            printf("Enter the key word u want to change:");
            scanf("%c", &search_key);
            // after this i don't have idea what to do....((((((


        }
    return 0;
}

enter code here

void read_str()
{
    int c;
    while((c = getc(stdin))!= '\n')
    *ptr1++ = c;
    *ptr1++ = ' ';
    *ptr1 = '\0';
}
+1  A: 

You will probably have to write your own function to do this, because I'm pretty sure there's nothing in stdio to do this (also, if you could just call a function, what would be the point of the homework assignment?). You can loop through the charaters in the input string, and when you find a sequence of characters that matches the string the user specified, you know you found a match. Then you have to replace the search string with some other string and output it. The output string will be everything before the search string, the replacement string, and everything after the search string.

FrustratedWithFormsDesigner
A: 

Just use strlen, strstr, strncpy, strncat. I'm not gonna write the program though :)

I'm pretty sure that goes beyond stdio.h, and if she could use them it would be a pretty pointless homework assignment.
FrustratedWithFormsDesigner
Unfortunately, one of the requirements of the assignment is to *not* use anything from string.h.
John Bode
A: 

Your search key-word can't be a single char if you want to change beautiful with clever! Instead you need a buffer, a char array like char search_key[SIZE] where SIZE is a constant big enough to hold the user input (the user could overflow the buffer, but I won't consider it a bug in homeworks).

So, you will use %s instead of %c in the scanf.

read_string can't access local variables of main. You should make them global (outside every function) or rather add arguments to read_string.

Note that the syntax s1[i] is the same as *(s1 + i) ... so the ideas I've tried to scatter in your previous closed question can be used as well, since array indexing in C is indeed pointer "math".

If you prefer using ptr1, where you read i++ in my prev code, change to ptr1++, where you read buf[i] change to *ptr1 simply (since it is already "positioned"); where you read to increment i to skip the word, just do a ptr1 += length of the word.

Instead of a dest buffer, likely you "need" simply to print; then change dbuf[j] = buf[i] with putchar(*ptr1), while in the case the comparison matched, use printf("clever") to write clever and increment ptr1 by the lenfth of beautiful as already said.

ShinTakezou
A: 

I'm not sure about homework policies on SO. So here is a starting point:

#include <stdio.h>

int main()
{
    char string[32]={0x0};
    sprintf(string, "%s", "first value");
    printf("%s\n", string);
    sprintf(string, "%s", "second value");
    printf("%s\n", string);
    return 0;
}

You do realize that your prof should be able to give you some hints. Plus it is extremely likely you covered this in class, so I don't feel like I'm giving you a total free ride.
If somebody else knows more about homework policy and this is not appropriate please clobber it.

jim mcnamara
The general rule is that it's OK to give hints, them nudges in the right direction, but try not to *do* the homeowork for them. Of course, nothing's physically preventing you from posting a working code solution, but you wouldn't really be helping them *learn*, only pass the course, and the two are not always the same thing.
FrustratedWithFormsDesigner
I've discussed this topic longly (on SO), so I won't do it again, just pointing that I did, and I disagree (in general) with this simplistic pedagogical vision. I like to repeat and repeat that students that do not want to learn, won't learn, while students that want to learn, will learn even analysing already made and working code.
ShinTakezou
hmm actually it's not an answer on my question...i'm not sooo toootaly noob in C, in order to not be able to write printf function..but anyway, thanks
Jeniffer
Shin Takezou, i'm not finish with ur advice yet. U know here's really nice forum, so many answers and so fast. I dont have a time to answer. Now i'll try urs
Jeniffer
@Jennifer take your time. printf sprintf ... are part of stdio, you should know them; anyway the code of this ans is not so useful for your task, so don't mind; @MnNamara there are question about homework policy on meta, but not rules: the only rule is that if the Q is "good", you're entitled to answer to help the OP as you think you help; people disagreeing on _how_ may downvote you even though your ans is right and useful to the OP (so I would count it as a reasonless downvote)
ShinTakezou
Shin - I moderate a set of forums that explicitly bans homework, except under very stringent conditions. We get one/two hw requests for help per month. This forums needs to seriously consider the homework issue. IMO. Your first version of student is far more common than you might care to think.
jim mcnamara
@Jeniffer - how is it possible to be working a final project and never having seen C code? Was all your classwork in COBOL?
jim mcnamara
A: 

You need to get the original text (your current attempt is flawed; you should pass s1 into the read_str() function yourself, and you might want to return the length of the string), and then read search_key as a string (look up scanf() and %s). Presumably you need replacement or some such string. Find how long each of these are (you can count characters until you hit \0).

You next need to find where search_key is in s1. Write yourself a function that takes two strings and checks to see if the characters are equal until you hit a \0. Then you can apply that function to s1 starting with the first character and continuing until you find it or run out of s1. (This isn't efficient, but it's easy and suitable for C homework.)

Now, you need a copy function, that will copy one string to another for a certain number of characters, and preferably also stopping with a \0. I wouldn't make it put a \0 at the end of what it copies, for this assignment. Make another string. Copy s1 in to the point where the search string starts. Copy the replacement string. Now, copy the rest of s1 from where the search string started plus the length of the search string, put a \0 at the end, and print out the string.

That should give you a direction to go in. If you have further problems, ask. SO works best for homework when critiquing code you've written.

David Thornley
+5  A: 

Well, several things immediately stand out.

First, the variable ptr1 is declared local to main, so the read_str() function won't be able to access it. Second, you can replace read_str() with a call to the fgets() library function (which is in stdio.h, so per the terms of the assignment is fair game) and get rid of read_str() entirely:

printf("Enter your string: ");
fflush(stdout); 

if (fgets(s1, sizeof s1, stdin)) // read into s1 directly
{
  // process string s1
}
else
{
  // error reading string
}

Since you want to replace whole words, you'll have to allocate search_key as an array of char, not a single char:

char search_key[SOME_SIZE_GREATER_THAN_1];

and you'll read it in the same way as the source string:

if (fgets(search_key, sizeof search_key, stdin))
...

I assume you will also need to get the replacement string as well:

char replacement[SOME_SIZE_GREATER_THAN_1];
...
if (fgets(replacement, sizeof replacement, stdin))
...

You could abstract these three operations out into a separate function, since they're all doing the same thing:

int getStr(const char *prompt, char *target, size_t targetSize)
{
  printf("%s:", prompt);
  fflush(stdout);
  if (fgets(target, targetSize, stdin) != NULL)
    return 1;
  else
    return 0;
}

and in your main function call it as

char s1[SIZE];
char search_key[SIZE];
char replacement[SIZE];
...
if (getStr("Enter your string", s1, sizeof s1))
{
  if (getStr("Enter the word you want to replace", search_key, sizeof search_key))
  {
    if (getStr("Enter the replacement string", replacement, sizeof replacement))
    {
      // do replacement
    }
  }
}

As for doing the actual replacement, that's the meat of the assignment, and I'm not sure how to give you hints without giving the whole thing away. Before tackling that, try just getting the input stuff working (read the source, target, and replacement strings).

EDIT

To answer some of Jennifer's questions below, here's how the overall program should be structured:

#include <stdio.h>
#define SIZE 100

/**
 * I prefer to define functions before they are used (at least within the same
 * translation unit, or file); the function definition is also a declaration,
 * so when the function is called later on in main(), the compiler already knows
 * what the right argument and return types are supposed to be.  If I defined
 * the function *after* main, I would still need a declaration for it before
 * I called it, and I would have to make sure the declaration and definition
 * matched up.  This way, it's just one less thing to worry about.
 *
 * It does mean that my code reads "backwards", though.    
 */  
int getStr(const char *prompt, char *target, size_t targetSize) 
{
  printf("%s:", prompt);
  fflush(stdout);
  if (fgets(target, targetSize, stdin) != NULL)
    return 1;
  else
    return 0;
}

/**
 * This would be a good place for a function to perform the replacement
 */

int main(void) // as of C99, just writing "main()" is no longer sufficient
{
  char s1[SIZE];
  char search_key[SIZE];
  char replacement[SIZE];

  if (getStr("Enter your string", s1, sizeof s1))
  {
    if (getStr("Enter the word to replace", search_key, sizeof search_key))
    {
      if (getStr("Enter the replacement string", replacement, sizeof replacement))
      {
        // do replacement
      }
    }
  }

  return 0;
}

Make sure your braces match up; the error you described sounds a lot like there was a mismatched brace (next time, copy and paste the exact error text). Type the above code in as written (minus the comments) and make sure you can get it to compile and run before doing anything else.

As for what you need to do in the section marked "do replacement", well, that's the meat of the assignment. One thing I will tell you is that if you want to store the result for later use, you will have to save it to yet another array (IOW, overwriting the original string won't work if the replacement text is longer than the source text; once you figure this out, you will understand why).

Again, it's going to be really hard to give you hints on how to do the replacement without essentially giving you the answer. You might want to work this out on paper first; write down your source, search, and target strings, and figure out the operations to find the search string in the source string (hint: you'll be looking at one character at a time in each string).

Work this assignment in several pieces; first, figure out how to read the strings from standard input (which I've done for you). Then figure out how you would search the source string for a specific character. Then figure out how you would search the source string for a sequence of characters. Once you get that far, the operations to perform the replacement should be fairly obvious.

But get the skeleton code above to build first.

John Bode
Just perfect expalanation! i finally got it=)
Jeniffer
+1 excellent "this is where to start" answer
Binary Worrier
i was joking to say that i got it.=( i have an error 'term doesn't evaluate a function taking 3 arguments' that function int getStr should it be void function after the main (like in my code)? in 'do replacement' what exactly?( cuz we suppose to get a new String with replaced word inside) so might be different function with smth printf("Your new string is:",charReplacement);
Jeniffer
@Jeniffer: Probably best to start a new question with the code that's causing the problem and examples of the input, expected output, and actual error message.
FrustratedWithFormsDesigner
@Jeniffer: see ShinTakezou's answer on your closed question for an explanation of that piece.
Larry Wang
@Jennifer: see edits above.
John Bode
@john: +1 again if I could, for having the patience of Job.
Binary Worrier
@Binary Worrier: it's either this or, you know, do actual *work*.
John Bode
@John Bode: (shudder) Speak no more of such *evil!!!*
Binary Worrier