C ++代码不在同一行显示输出

时间:2018-01-06 05:52:49

标签: c++

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

在运行代码时,编译器在不同的行中提供输出,如: - How the program is working on execution

4 个答案:

答案 0 :(得分:1)

fgets()是一个文件函数,用于从键盘读取文本,如“file get string”。 fgets()函数读取字符串以及“输入”字符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;
}

You can see the output in attached screenshort

答案 1 :(得分:0)

尝试用str中的''替换'\ r \ n'和'\ n \ r'替换

在这里查看字符串中的替换:How to replace all occurrences of a character in string?

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

使用fgets()时,您还会在输入中获得结束换行符。这解释了你的输出。您可以使用std::getline来避免此问题。

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