This question already has answers here:
Removing trailing newline character from fgets() input
(13个回答)
2年前关闭。
在运行代码时,编译器在不同的行中给出输出,例如:
![c++ - C++代码未在同一行中显示输出-LMLPHP c++ - C++代码未在同一行中显示输出-LMLPHP]()
(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 ;
}
在运行代码时,编译器在不同的行中给出输出,例如:
最佳答案
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++ - C++代码未在同一行中显示输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48124716/