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\ncharacter into (C++) string s;cin >> sdoes 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)cThat'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,
fgetsis C-Style function, whilegetlineis for C++ ..So, from this difference, you can conclude that
fgetsworks with C-strings orchar[]orchar*, whilegetlineworks with normal stings.PS: There's a
getlineas a member function of cin, that takes C-strings, asfgets, or the non-member functiongetlinethat takes a stream and a string.How to use each? 1. using
fgetsI 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.