【问题标题】:Alternative Method from c to c++从 c 到 c++ 的替代方法
【发布时间】:2011-04-04 17:16:03
【问题描述】:

是否有另一种方法可以使用 scanfprintf 函数在 C++ 中重写相同的脚本? 谢谢!

    #include <stdlib.h>
    #include <stdio.h>

    int main( int argc, char * argv[], char* env[]) {
    char quer[222];

    printf("Content-type: text/plain\n\n");

    scanf("%s",quer);
    printf("%s\n",quer);
    return 0;
    }

【问题讨论】:

  • 为什么?除了容易修复的缓冲区溢出之外,这段代码还有什么问题?
  • 主要接受无参数或 2 个参数。按照标准。
  • @Nyan - 该标准还允许main() 的其他实现定义的签名。第三个参数指向环境块是很常见的。

标签: c++ c rewrite scanf


【解决方案1】:
#include <iostream>
#include <string>

int main()
{
    std::cout << "Content-type: text/plain\n\n";

    std::string quer;
    std::getline(std::cin, quer);
    std::cout << quer << '\n';
}

【讨论】:

    【解决方案2】:

    这个? (注:此代码未经编译或测试。)

    int main(int ac, char **av) {
        std::string quer;
        std::cout << "Content-type: text/plain\n\n";
        std::cin >> quer;
        std::cout << quer << "\n";
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 C++ iostream。

      #include <iostream>
      #include <string>
      using namespace std;
      
      int main()
      {
          string quer;
          cout << "Content-type: text/plain" << endl;
          cin >> quer;
          cout << quer;
          return 0;
      }
      

      【讨论】:

      • 只是为了指出。您声明“使用命名空间 std”,然后在代码中您有时专门引用一个类型,即 std::string,但在其他时候您没有专门引用它。即cincout。我建议以一种或另一种方式进行。特别像@Mike Seymour 在上述答案中所做的那样。
      • 清理后的答案更加一致。
      【解决方案4】:

      这取决于平台,但在 Unix(或换行符为 \n 的任何平台)上,这应该是错误兼容的。

      #include <stdio.h>
      #include <stdlib.h>
      
      int main( int argc, char * argv[])
      {
          char quer[222];
      
          puts("Content-type: text/plain\n");
      
          gets(quer);
          puts(quer);
          return 0;
      }
      

      但鉴于 C++ 解决方案是可以接受的,我建议将 cinstringgetlinecout 用于 I/O。

      【讨论】:

        【解决方案5】:

        我不确定原因是什么....但您也可以使用 cin/cout 代替您那里的 scanf/printf。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-23
          • 1970-01-01
          • 1970-01-01
          • 2014-01-23
          • 2021-09-11
          • 1970-01-01
          • 2015-11-04
          • 1970-01-01
          相关资源
          最近更新 更多