1
#include<iostream>
using namespace std;

int main()
{
    char str[10] = "Anmol" ;
    int age = 17 ;
    cout << "Enter your name here :- " ;
    fgets(str, sizeof(str), stdin) ;
    cout << "Enter your age here :- " ;
    cin >> age ;
    cout << "Hello World, It's " << str << "And my age is " << age ;
    return 0 ;
}

On running the code, the compiler is giving output in different line like:- How the program is working on execution

slothfulwave612
  • 1,349
  • 9
  • 22
  • I think that fgets is catching the enter that you use to send age, verify it. – eyllanesc Jan 06 '18 at 06:00
  • `fgets` leaves a newline in the string. Use getline. – Retired Ninja Jan 06 '18 at 06:00
  • After reading using `fgets()`, checking `str[strlen(str)-1]` will contain a `'\n'` i.e. a newline character (unless the user enters a name with more than 9 characters). That's how `fgets()` works. – Peter Jan 06 '18 at 06:45

4 Answers4

2

fgets() is a file function which is used to read text from keyboard, as in “file get string.” fgets() function is read the string as well as "enter" character ascii code which is 13 (carriage return - CR) .so the above code consider the CR character at the end of the 'str' that's why it print in the next line .

You can use the gets_s() function to take the string from the keyboard. Try the below code .

#include<iostream>
using namespace std;

int main()
{
    char str[10] = "Anmol";
    int age = 17;
    cout << "Enter your name here :- ";
    gets_s(str);
    cout << "Enter your age here :- ";
    cin >> age;
    cout << "Hello World, It's " << str << " And my age is " << age;
    return 0;
}

You can see the output in attached screenshort

Usman
  • 1,983
  • 15
  • 28
1

try replace '\r\n', and '\n\r' with '' in str

look at here for replace in string : How to replace all occurrences of a character in string?

Hossein Badrnezhad
  • 424
  • 1
  • 6
  • 18
  • 1
    Given that OP is using [XTerm](http://invisible-island.net/xterm/), I doubt they have Windows newlines. However, all newlines will simply be read as a C++ `\n` character. – chris Jan 06 '18 at 06:04
1

Try this:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    int age;
    cout << "Enter your name here :- " ;
    cin >> str;
    cout << "Enter your age here :- " ;
    cin >> age ;
    cout << "Hello World, It's " << str 
         << " And my age is " << age << endl;
    return 0 ;
}
Sid S
  • 6,037
  • 2
  • 18
  • 24
1

When you use fgets(), you also get the ending newline character in the input. That explains your output. You could use std::getline to avoid that problem.


int main()
{
   std::string str = "Anmol" ;
   int age = 17 ;
   cout << "Enter your name here :- " ;
   std::getline((std::cin, str) ;
   cout << "Enter your age here :- " ;
   cin >> age ;
   cout << "Hello World, It's " << str << " and my age is " << age << std::endl;
   return 0 ;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270