This question already has answers here:
Removing trailing newline character from fgets() input

(13个回答)


2年前关闭。



#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 ;
}

在运行代码时,编译器在不同的行中给出输出,例如:
c&#43;&#43; - C&#43;&#43;代码未在同一行中显示输出-LMLPHP

最佳答案

fgets()是一个文件函数,用于从键盘读取文本,如“file get string”。
fgets()函数将读取字符串以及“enter”字符ascii代码(13(回车-CR))。因此,上面的代码考虑了'str'末尾的CR字符,这就是为什么它在下一个打印线。

您可以使用gets_s()函数从键盘上获取字符串。
试试下面的代码。

#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;
}

c&#43;&#43; - C&#43;&#43;代码未在同一行中显示输出-LMLPHP

关于c++ - C++代码未在同一行中显示输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48124716/

10-11 12:38
查看更多