4

Possible Duplicate:
Reading string from input with space character?

I am facing problem in taking a string(technically character array) as input. Suppose i have the following declaration:

 char* s;

I have to input a string using this char pointer till i hit "enter", please help! Thanx in advance.

5
  • 9
    "C/C++" is still not a language. Decide which one you want, because the two differ in the idiomatic way of programming user interaction. Commented Dec 24, 2012 at 14:47
  • actually, i am facing this problem in both of the languages. The reason i mentioned it as C/C++ :) Commented Dec 24, 2012 at 14:51
  • @user1916200 The solutions for the two languages are drastically different in complexity. Commented Dec 24, 2012 at 14:51
  • Well, the solution is similar but not the same, so for THIS question, which do you want the answer for? Commented Dec 24, 2012 at 14:52
  • please help me in doing so in both the languages separately. Commented Dec 24, 2012 at 15:00

6 Answers 6

9

In both C and C++ you can use the fgets function, which reads a string up to the new line. For example

char *s=malloc(sizeof(char)*MAX_LEN);
fgets(s, MAX_LEN, stdin);

will do what you want (in C). In C++, the code is similar

char *s=new char[MAX_LEN];
fgets(s, MAX_LEN, stdin);

C++ also supports the std::string class, which is a dynamic sequence of characters. More about the string library: http://www.cplusplus.com/reference/string/string/. If you decide to use strings, then you can read a whole line by writing:

std::string s;
std::getline(std::cin, s);

Where to find: the fgets procedure can be found at the header <string.h>, or <cstring> for C++. The malloc function can be found at <stdlib.h> for C, and <cstdlib> for C++. Finally, the std::string class, with the std::getline function are found at the file <string>.

Advice(for C++): if you are not sure which one to use, C-style string or std::string, from my experience I tell you that the string class is much more easy to use, it offers more utilities, and it is also much faster than the C-style strings. This is a part from C++ primer:

As is happens, on average, the string class implementation executes considerably
faster than the C-style string functions. The relative average execution times on
our more than five-year-old PC are as follows:

    user            0.4   # string class
    user            2.55  # C-style strings
Sign up to request clarification or add additional context in comments.

Comments

2

First thing is to take input into this string you have to allocate memory. After that you can use gets or fgets or scanf

4 Comments

Bad idea to use gets! Use fgets(var, size, stdin) instead.
Yes thats true. I thought to add that point but i missed
okay, i don't know in advance as to how many characters would there be int the string. What all i know is that i have to stop processing the input as and when i hit enter
You can read one character at a time using getc and allocate memory using realloc as you read !!!
1

If you think about C++, cin.getline() might be useful.

1 Comment

And there needs to be memory allocation as well!
1

You can use cin>>variable_name; if input is without space. For input with space use gets(variable_name) in c++

1 Comment

If your compiler compiles code that uses gets, get rid of the compiler. If you have an application that you know to be one that uses gets, get rid of that application. If you or anyone you know actually recommends gets, (get him/her/them to) take a look at the Wikipedia entry for buffer overflow.
0

the s should be allocated before starting filling on it

1) If you do not know in advance the size of inputed string you can use realloc

char* s = calloc(1,sizeof(char));
char t;
int len;
while(scanf("%c", &t)==1)
{
  if(t== '\n')
     break;
   len = strlen(s);
   s= realloc(s,len+1);
   *(s+len) = t;
   *(s+len+1) = '\0';
}

2) Now If you know in advance the size of your input string max length, you can read directly your string into an array of char with scanf in this way:

char s[256] // Let's assume that the max length of your input string is 256

scanf("%[^\r\n]",s) // this will read your input characters till you heat enter even if your string contains spaces

Comments

-1

Hmmm, since the OP has stated:

I have to input a string using this char pointer till i hit "enter"

Thought I'd give this a shot, top of my head, this is a dynamic buffer, using malloc and realloc using pointers. However, it may contain bugs, but the gist is there! Nitpicky aside...

Apologies if the code does look awful... ::)

char *ptr = NULL, *temp_ptr = NULL;
int c = 0, chcount = 0, enter_pressed = 0;
do{
   c = fgetc(stdin);
   if (c != '\n' || c != -1){
     chcount++;
     if (ptr == NULL){
         ptr = malloc(sizeof(char) + chcount + 1);
         if (ptr != NULL) ptr[chcount] = c;
         else printf("ABORT!\n");
     }else{
         temp_ptr = realloc(ptr, chcount + 1);
         if (temp_ptr != NULL){
            ptr = temp_ptr;
            ptr[chcount] = c;
         }else{
            // OK! Out of memory issue, how is that handled?
            break;
         }
     }
   }else{
      enter_pressed = 1;
   }
}while (!enter_pressed);
ptr[chcount] = '\0'; // nul terminate it!

5 Comments

As I have stated - its top of my head in what the OP is looking for and did warn that the code may be awful to look at :)
Kill the malloc() and just make sure ptr is NULL on inception (which it is).
@WhozCraig your comment, the last wording, inception? Oo
i.e. make sure its initialized to NULL prior to the start of the loop (and yours is NULL, so good). realloc() behaves like malloc() when the input pointer is NULL. (side note: its a common joke that one can implement most-all the C memory allocation functions using just realloc() and preprocessor macros).
@WhozCraig yes I am aware of realloc and had to use it separately as not to confuse - in fact realloc is a classic example of function overload ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.