abhi-kumar's blog

By abhi-kumar, 11 years ago, In English

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.

  • Vote: I like it
  • -7
  • Vote: I do not like it

| Write comment?
»
11 years ago, # |
  Vote: I like it +1 Vote: I do not like it

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 character

  • scanf(" %s",c) reads all characters up till the next whitespace into the array char c[size]; this can be converted to a C++ string as s =(string)c

That's all I ever needed.

  • »
    »
    11 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    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:

    #include <bits/stdc++.h>
    
    using namespace std;
    
    main()
    {
    char a[5];
    fgets (a,3,stdin);
    printf("%s",a);
    }
    
    

    INPUT: 12345

    OUTPUT: 12

  • »
    »
    11 years ago, # ^ |
    Rev. 3   Vote: I like it -8 Vote: I do not like it

    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.

    • »
      »
      »
      11 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like 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.

»
11 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Okay main difference, fgets is C-Style function, while getline is for C++ ..

So, from this difference, you can conclude that fgets works with C-strings or char[] or char*, while getline works with normal stings.

PS: There's a getline as a member function of cin, that takes C-strings, as fgets, or the non-member function getline that takes a stream and a string.

How to use each? 1. using fgets

#include <cstdio>
// Assuming the line you will read is 1000
#define MAX_LINE_SIZE 1000  
char line[MAX_LINE_SIZE + 1]; // Allocate 1 more space for the NULL terminator.

int main() {
    // The first arg, is the char[] you will read the input in.
    // The second arg, is the MAXIMUM amount of characters you want to read.
    // The third arg, is the stream you want to read from.
    fgets(line, MAX_LINE_SIZE + 1, stdin);
    // The function works as reading all characters from the stream provided, until it reaches a \r\n or \n or it reads the max number of characters.
    // You define the MAX CHARS READ, so as to avoid running out of allocated memory for the char[] as it's static.
    
    // Then line is a cstring, you can work with any cstring function. If you want to change it to a normal string, just use string(line)
    printf("%d\n", strlen(line));
    printf("%s\n", line);

    string s = string(line);
    return 0;
}
  1. Using getline():
#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

int main() {
     string s;
     getline(cin, s);
     // Now the function reads all the characters until the next \r\n or \n, and you don't need to worry about CHARS READ as a string can expand in size.

     cout << "Length read is: " << s.length() << endl;
     cout << "String read is: " << s << endl;
     
    //if you need to convert it to a char*, just use the .c_str() function in the string.
    char* cstr = (char*) s.c_str();
 


     return 0;
}

I hope it helps.

  • »
    »
    11 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    The code where you said about c_str, won't compile:

    Can't compile program.cpp:
    program.cpp: In function 'int main()':
    program.cpp:17:26: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
    

    So when you work with c_str, you'll need either to use const char * instead of char * (and then you won't be able to modify it) or copy the characters from your const char * string to another, non-const. It's restriction of STL.

    For example, the following code will work as you expect:

    #include <iostream>
    #include <cstdio>
    #include <string>
    
    using namespace std;
    
    int main() {
        string s;
        getline(cin, s);
    
        const char* cstr;
        cstr = s.c_str();
    
        cout << "cstr: " << cstr << "\n";
    
        return 0;
    }
    
    • »
      »
      »
      11 years ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Aha, I forgot that part, you can simply cast it to char* by doing char* cstr = (char*) s.c_str()

      • »
        »
        »
        »
        11 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Hmm, interesting. Didn't know that this is possible

      • »
        »
        »
        »
        11 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        But if you dereference that, you could cause undefined behavior.