hello coders, i m new to the programming platforms so can someone help me in taking the string as input.i have lots of confusion in using (fgets) and (getline) .please explain the differences between (fgets) and (getline) and how to use them. Thanks in advance.
You don't need to use fgets().
There are 2 main ways to read strings:
getline(cin,s)
reads the input up till the next\n
character into (C++) string s;cin >> s
does the same, but up till the next whitespace characterscanf(" %s",c)
reads all characters up till the next whitespace into the arraychar c[size]
; this can be converted to a C++ string ass =(string)c
That's all I ever needed.
Well, but he asked, what is fgets.
If you need to read only k characters (including terminating '\0') from the input, you can use fgets.
For example:
INPUT: 12345
OUTPUT: 12
1.will i have to convert character array into strings to use getline? exmple:
include
include<stdio.h>
include<string.h>
using namespace std;
int main() { char c[10]; string s; s=(string)c; getline(cin,s); cout<<s; } input:abhishek kumar output:abhishek kumar 2.how can i use (strlen) function while using (getline).i have tried but not able to use it.
I suggest you don't try to mix C++ and C — you're including libraries of C, and the length of a C++ string s is given by
s.length()
.You don't initialize the array c, so it will contain rubbish, and after
s=(sring)c
, s will contain rubbish.Look at your code and think about what it does with c. The answer is: nothing. You don't put any data into it, you just have it exist, and that's wrong.
Okay main difference,
fgets
is C-Style function, whilegetline
is for C++ ..So, from this difference, you can conclude that
fgets
works with C-strings orchar[]
orchar*
, whilegetline
works with normal stings.PS: There's a
getline
as a member function of cin, that takes C-strings, asfgets
, or the non-member functiongetline
that takes a stream and a string.How to use each? 1. using
fgets
I hope it helps.
The code where you said about c_str, won't compile:
So when you work with
c_str
, you'll need either to useconst char *
instead ofchar *
(and then you won't be able to modify it) or copy the characters from yourconst char *
string to another, non-const. It's restriction of STL.For example, the following code will work as you expect:
Aha, I forgot that part, you can simply cast it to
char*
by doingchar* cstr = (char*) s.c_str()
Hmm, interesting. Didn't know that this is possible
But if you dereference that, you could cause undefined behavior.