take string input using char* in C and C++

37,373

Solution 1

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

Solution 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

Solution 3

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

Solution 4

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

Share:
37,373
user1916200
Author by

user1916200

Updated on August 17, 2022

Comments

  • user1916200
    user1916200 over 1 year

    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.