storing string

This is a discussion on storing string within the C Programming forums, part of the General Programming Boards category; Hi All, I am trying to storing a string of text in to a variable, but I dont know which ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    5

    storing string

    Hi All,

    I am trying to storing a string of text in to a variable, but I dont know which data type I should use. Unlike VB6, C doesn't have String variable. char can only store a character at time(if I not wrong). The problem of using the array is that it is unknown length of text, therefore I can not set the array size. I know that there is something calls vector in C++. But in this assignment, we are not suppose to use vector as we not there yet.

    Thank you very much for any input.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    You'll want an array of char. For dynamic allocation, look into malloc. Please also visit the FAQ.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,231
    The simplest way is using a fixed size array. Otherwise it gets complicated:
    You should allocate some memory and add to it each time you are getting more chars.
    If you are using C++ you can use string data-type by including <string> header.
    C99 has VLA that I don't know can help or not (I'm not sure if its size can be changed in that way).
    Last edited by siavoshkc; 09-30-2006 at 12:39 PM.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    5
    Code:
    main()
    {
    
           char *ptText;//pointer
           int intCnt = 0;//is a number of character in the array
           ptText = malloc(intCnt * sizeof(int)); //allocate the memory
    
           printf("Please enter your text: \n");
    
            while(getchar() !='\n')
             {
                     scanf("%s", ptText[intCnt]);
                      ptText[intCnt] = getchar(); // assign to the array using pointer
                      intCnt++; //counter
               }
    
                printf("You have entered \%s\n", ptText);
               return  0;
    
    }
    Please see what I did wrong as the program is not run. The purpose of the program is to take the string of text (unknown of lenght) from input and output it. The problem is we dont know the length of the text string. otherwise i'd use the pre-determined arrary size.

    Thanks.
    Last edited by Dave_Sinkula; 09-30-2006 at 06:50 PM. Reason: Added [code][/code] tags -- learn to use them yourself.

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Well, you'll probably need to start with more than zero characters of space. And then realloc as things grow. And remember to make the string 1 larger for the null character.

    As you are reading in each character, you'll want to store it instead of merely discarding it. And don't use scanf like that -- with %s -- and don't mix it with getchar.

    There is an FAQ on reading text from the user. It uses a fixed buffer, and so can you if you then realloc only when you've exceeded that size.

    [edit]This really amounts to implementing something akin to C++'s getline for string in C, which would seem to be less than a trivial exercise.
    Last edited by Dave_Sinkula; 09-30-2006 at 08:34 PM. Reason: ...
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    5
    I did some modifications as you to, still not runing. Can you please tell me what is wrong, more specific. I've spent all day, today tried to figure out but no success. Please help. Thanks.

    main()
    {

    char ch; //declare the variable
    char *ptText;//pointer
    int intCnt = 1;//is a number of character in the array
    ptText = malloc(intCnt * sizeof(int)); //allocate the memory

    printf("Please enter your text: \n");
    ch = getchar();

    while(ch !='\n')
    {
    intCnt++;
    ch = getchar();
    ptText[intCnt] = ch;
    printf("You have entered: \%c\n\", ptText[intCnt]);
    }

    return 0;

    }

  7. #7
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,231
    This is a code by Bjarne Stroustrup. {EDITED}

    Code:
    #define TRUE 1
    #define FALSE 0
    void quit()    /*write error message and quit*/
    {
        fprintf(stderr,"memory exhausted\n");
        exit(1);
    }
    int main()
    {
        int i;
        int max = 20;
        char* name=(char*) malloc(max);   /*allocate buffer*/
        if(name == 0) quit();
        printf("Please enter your first name:\n");
        while(TRUE){                /*skip leading white space*/
              int c = getchar();
              if(c == EOF) break;   /*end of file*/
              if(!isspace(c)){
                    ungetc(c, stdin);
                    break;
              }
        }
        
          i = 0;
        while(TRUE){
              int c = getchar();
              if(c == '\n'|| c == EOF){   /*at end; add terminating zero*/
                    name[i] = 0;
                    break;
              }
              name[i] = c;
              if(i == max-1){    /*buffer full*/
                    max = max + max;
                    name =(char*)realloc(name,max);  /*get a new and larger buffer*/
                    if(name == 0)quit();
              }
              i++;
        }
        printf("Hello %s\n", name);
        free(name);   /*release memory*/
        return 0;
    }
    Please explain your program logic and what you are trying to do.
    Last edited by siavoshkc; 10-01-2006 at 12:05 PM.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,663
    - read a line fragment into a fixed-length buffer using fgets
    - allocate space to store the string fragment
    - copy the buffer to the allocated space.
    - repeat until you get the "end of the string", whatever you consider that to be (say EOF or a newline).

    How you manage your very long string in memory is up to you - a single large string or a linked list of fragments is equally possible.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    I don't see the point declaring a buffer as a pointer, why can't you simply do it like this:
    Code:
    char name[256];
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,663
    > This is a code by Bjarne Stroustrup.
    Wow - I would never have thought Bjarne would be capable of that level of incompetence at writing a C program. Where did you find this code of his?

    > void quit() / /write error message and quit
    This isn't even a C++ comment, nevermind a C comment.

    > char* name=(char*) malloc(max);
    Casting malloc in C is poor form.

    > while(true)
    true isn't a C keyword.

    > int i = 0;
    C doesn't support embedded declarations.

    > name =(char*)realloc(name,max);
    Classic realloc usage bug - if realloc fails, you have a memory leak.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,231
    Where did you find this code of his?
    His site. An article named "Learning Standard C++ as a New Language".

    > void quit() / /write error message and quit
    This isn't even a C++ comment, nevermind a C comment.
    It is is my mistake not Stroustrup's.

    true isn't a C keyword.
    I noted at the end of post.

    I think Stroustrup was writing this code in a C++ compiler.

    > name =(char*)realloc(name,max);
    Classic realloc usage bug - if realloc fails, you have a memory leak.
    I don't know. Maybe he wanted to keep the code simple.

    char name[256];
    What if the user input was more that 256 chars?
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    5
    What is 'true'?

    When I compiled, it say 'true' undelared (first use in this function).

    Thanks.

  13. #13
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,231
    I edited the code. Recompile it.
    True is a C++ keyword. But has no meaning for C compiler. You should add that "#define true 1 [edit: deleted].
    Last edited by siavoshkc; 10-01-2006 at 11:40 AM.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  14. #14
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,738
    Quote Originally Posted by Salem
    > while(true)
    true isn't a C keyword.
    Well, in fact everything Salem mentioned is a problem, as we are compiling C.
    You just need to make a few changes to get Mr. Stroustrup's code to work:
    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    void quit(void) {
        fprintf(stderr, "memory exhausted.\n");
        exit(EXIT_FAILURE);
    }
    
    int main(void) {
        size_t max = 20;
        char *name = malloc(max);
        char *morename;
        int ch, i;
    
        if (name == NULL) quit();
        printf("Please enter your name: \n");
        /* skipping whitespace */
        do
           ch = getchar();
        while (ch != EOF && isspace(ch));
        ungetc(ch, stdin);
    
        for (i = 0; ; i++) /* add terminating zero */
        {
            ch = getchar();
            if (ch == '\n' || ch == EOF)
            {
                name[i] = '\0';
                break;
            }
            name[i] = ch;
            if (i == max - 1) /* buffer full */
            {
                max = max + max;
                morename = realloc(name, max);
                if (morename == NULL)
                {
                    free(name);
                    name = NULL;
                    quit();
                }
                name = morename;
            }
        }
        printf("Hello %s.\n", name);
        free(name);
        return EXIT_SUCCESS;
    }

  15. #15
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,231
    I edited it to be fully C compliant.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21