Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

take string input using char* in C and C++ [duplicate]

Tags:

c++

c

string

input

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.

like image 562
user1916200 Avatar asked Dec 15 '22 15:12

user1916200


1 Answers

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
like image 66
Rontogiannis Aristofanis Avatar answered Dec 29 '22 00:12

Rontogiannis Aristofanis