【问题标题】:Why is this code not taking input for "Designation"?为什么此代码不接受“指定”的输入?
【发布时间】:2017-01-10 17:39:59
【问题描述】:

从屏幕截图中可以看出,fgets() 函数只运行一次以接收字符串name,但它不接受designation 字符串并跳到“salary”输入。更让我感兴趣的是,同样的代码在 TurboC3 中运行得非常好......我只遇到基于 GCC 编译器的 IDE(例如 DevCPP)以及现在在 Linux 中的 GCC 本身中遇到的问题。

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <string.h>
using namespace std;

class emp
{
private:
    char name[20], desig[20];
    int id;
    float salary;

public:
    void getdata()
    {
        cout << "ENTER NAME:\n";
        fgets(name, 20, stdin);
        cout << "ENTER ID:\n";
        cin >> id;
        cout << "ENTER DESIGNATION:\n";
        fgets(desig, 20, stdin);
        cout << "ENTER SALARY:\n";
        cin >> salary;
    }

    void showdata()
    {
        cout << "NAME:- " << name << "\n";
        cout << "ID:- " << id << "\n";
        cout << "DESIGNATION: " << desig << "\n";
        cout << "SALARY: " << salary << "\n";
    }
};

int main()

{

    emp ins[3];
    int i;
    cout << "ENTER DETAILS:\n";
    for (i = 0; i < 3; i++)
        ins[i].getdata();
    cout << "*****************************DETAILS***************************\n";

    for (i = 0; i < 3; i++)
        ins[i].showdata();
    return 0;
}

【问题讨论】:

  • 我已通过将标题转换为小写来编辑您的问题。一般而言,以英语为母语的人会认为全部大写字母会大声喊叫,这种感觉很差。希望这次修改能吸引更多有用的反馈。

标签: c++ class gcc


【解决方案1】:

从标准输入读取时,不要混合使用 C 库函数,例如 fgets() 和 C++ std::cin 运算符。 C 库对 C++ 库在做什么一无所知。

将您的代码更改为仅使用 stdin 或仅使用 std::cin 来读取标准输入。

【讨论】:

    【解决方案2】:

    不要混合 C 和 C++ 输入流

    使用stdin 或istream。换句话说,这意味着不要在同一区域同时使用fgets() 和cin。使用其中一种。要读取带有空格的完整字符串,请使用std::getline(std::cin, input)

    【讨论】:

    • 谢谢......它成功了............学到了一些新东西......并且还了解到 TurboC3 不应该用于学习 C++,因为它混合了 C 和 C++跨度>
    【解决方案3】:

    thanx 伙计们......你的提示有所帮助......但是......我做了更多的研究,发现我可以在没有字符串类型字符串的情况下使用 getline......(即由字符数组组成的字符串)使用 cin.getline(string_name,string_size).....这更方便,因为这个 wud 让我可以毫无问题地使用所有传统的字符串函数.....thanx 再次......

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2016-06-05
      • 1970-01-01
      相关资源
      最近更新 更多