dev 为什么在 dev c++ 中使用 "cin function" 后我无法使用"gets function"?

dev why I can't use "gets function" after using "cin function" in dev c++?

本文关键字:dev function gets cin c++ 为什么      更新时间:2023-10-16

下面是我的代码:

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
main()
{
      char a[120];
      int b;
      cout<<"age : ";
      cin>>b;
      cout<<"Name : ";
      gets(a);
      cout<<"Name : "<<a<<endl;
      cout<<"age  : "<<b;
      cout<<endl;
      system("pause");
      return 0;
}

输出:age: 20//我输入20Name: Name://它不要求输入Name。年龄:20岁按任意键继续…

但是,如果我先使用gets(a),就可以了

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
main()
{
      char a[120];
      int b;
      cout<<"Name : ";
      gets(a);
      cout<<"age : ";
      cin>>b;
      cout<<"Name : "<<a<<endl;
      cout<<"age  : "<<b;
      cout<<endl;
      system("pause");
      return 0;
}

输出:Name: John//输入John。age: 20//I type 20.

姓名:John年龄:20岁按任意键继续…

他们怎么了?

无论你现在正在学习什么书/网络教程,把它扔掉。不,我是认真的。这段代码读起来好像是1992年写的。以下是Stack Overflow社区推荐的书籍列表。

同样,如果你的dev - c++版本是4.9.9.2,我强烈建议你升级——更新的IDE将提供更好的编辑器、更好的调试器和(非常重要的)更好的编译器。更好的编译器会给你更好的错误信息,这在学习c++时很重要(相信我,我从经验中知道),常见的替代方案是:Visual c++, Code::Blocks,或者如果你喜欢dev - c++,就升级到Orwell dev - c++。

让我们快进到2013年。

有几个笑话可以简化为"meh,我听错误而不是警告"。他们错了。95%的警告意味着代码是错误的。由于c++是一种复杂的语言,每个人都应该在他们的ide中启用警告(我很困惑为什么没有默认启用)。

<

头/strong>

在c++中引入命名空间意味着旧的头文件已被弃用。这意味着在编写新代码时不应该使用它们。

头文件的名称是这样修改的:

  • 内置c++头文件末尾没有".h"。("iostream.h" -> "iostream")

  • 源自C的头文件不以"。h"结尾,并且以"C"("stdio.h"->"cstdio")作为前缀

  • conio.h既不是内置的C头文件,也不是内置的c++头文件,所以名称保持不变。

这里是标准标头列表

字符串

c++有字符串类型。std::string。它允许简单的字符串操作,没有麻烦。只要#include <string>使用它。

string first_name = "John";
string surname = "Titor";
string full_name = first_name + " " + surname; //easy concatenation
//string a = "first" + " " + "name" //nasty surprise
string c = "first" + string(" ") + "name" //much better
//or using stringstream (#include <sstream>)
stringstream ss;
ss << "first" << " " << "name";
c = ss.str();

gets ()

这个函数是不可能安全使用的——它不限制用户输入也不扩展缓冲区。在您的示例代码中,有人可能输入超过120个字符,并最终调用未定义行为。这一项相当于数学中的未定义行为——任何事情都可能发生,包括1等于2。gets()函数最近从C语言中删除了。c++有一个安全的替代方案。

string s;
getline(cin, s);

main()

int main()

int main(int argc, char* argv[])

避免同时使用iostream和stdio的函数。

但是,您的问题是由额外的Enter引起的。

当您输入age并按enter键时,cin只消耗该数字。Enter被传递给gets(),所以它直接返回。

可以是

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
main()
{
    char a[120];
    int b;
    cout<<"age : ";
    cin>>b;
    cin.ignore();  //add this line to eat the enter
    cout<<"Name : "<<flush;
    gets(a);
    cout<<"Name : "<<a<<endl;
    cout<<"age  : "<<b;
    cout<<endl;
    system("pause");
    return 0;
}