【问题标题】:Taking Input through a string in c++在 C++ 中通过字符串获取输入
【发布时间】:2012-10-12 10:55:39
【问题描述】:

在 C 语言中,假设我需要从字符串中获取输入

 int num,cost;
 char *name[10];
 printf("Enter your  inputs [quantity item_of_name at cost]");
 scanf("%d%*c%s%*c%*s%*c%d",&num,name[0],&cost);

 printf("quantity of item: %d",num);
 printf("the cost of item is: %d",cost);
 printf("the name of item is: %d",name[0]);

输入

12 点出书

输出

商品数量:1

物品的成本是:12

物品名称是:书

现在我想在 C++ 中做同样的事情。我不知道如何接近。 gets() 返回整个字符串。是否有我遗漏的特定函数?请帮忙。

【问题讨论】:

  • 您的问题有点混乱,因为您的 C 代码不是从字符串而是从标准输入获取输入。你真正想做什么?此外,您使用的 C 函数也可以在 C++ 中使用。
  • 他的 C 代码无论如何都坏了:他将一个未初始化的指针作为第三个参数传递给 scanf。即使它已被初始化:用户可以使用足够长的名称轻松地使程序崩溃。在 C 中,您从不scanf 中使用 "%s" 而不指定最大长度。
  • 我正在尝试使用格式说明符将适当的输入(在字符串中)存储到相应的变量中。现在我从未见过在 C++ 中使用 C 函数(或我们在 C 中使用的函数)。 (我不是说你不能......只是我还是个初学者)。基本上我试图将问题从 C 转换为 C++。
  • @Peps C++ 的输入方式由 sehe 给出,但 C 方式也可以。

标签: c++ c string input


【解决方案1】:
int num,cost;
std::string name;
std::cout << "Enter your  inputs [quantity item_of_name at cost]: ";
if (std::cin >> num >> name >> cost)
{ } else 
{ /* error */ }

你会想要添加错误处理

【讨论】:

    【解决方案2】:

    在 C++ 中,您应该使用标准库中的 cincoutstring

    【讨论】:

      【解决方案3】:

      在 c++ 中,std::stream 通过&gt;&gt; 运算符提供与用户的读写通信。

      您的代码转换为

      int num,cost;
      std::string name;
      
      std::cout << "Enter your  inputs [quantity item_of_name at cost]" << std::flush;
      std::cin >> num >> name;
      std::cin >> at; // skip the at word
      std::cin >> cost;
      
      std::cout << "quantity of item: " << num << std::endl;
      std::cout << "the cost of item is: " << cost << std::endl;
      std::cout << "the name of item is: " << name << std::endl;
      

      【讨论】:

        【解决方案4】:

        您可以使用 iostream 的 cin。

        int num,cost;
         char *name[10];
         std::cout <<"Enter your quantity"<<std::endl;
         std::cin>> num;
         std::cout<<" Enter the cost"<<std::endl;
         std::cin>>cost;
         std::cout<<"Enter the name"<<std::endl;
        
         std::cout<<"The quantity of the item is: "<<num<<" costing: "<<cost<<" for "<<name[0]<<std::endl;
        

        当然你也可以使用 std::string 代替 char*。

        或者将cin的精简为cin >> num >> cost >> name;

        此外,正如 Griwes 所述,您需要对结果执行错误检查。

        【讨论】:

        • 是的,但我想这是不言而喻的。
        • OP 看起来像新手(一般来说,他看起来像是受过教育的人,C++ 只是“C with classes”并教授了一些 C 基础知识),所以我认为这里很重要。
        • 我的假设是,因为他正在使用(很清楚如何)一个 char 指针数组,所以他知道错误处理,但在我的镇静中并没有停下来考虑这可能是一个家庭作业问题并且刚刚提供了该代码。很好的收获,也注意到了。
        • 您的代码产生与提问者相同的未定义行为。最好用should 替换could 并告诉他/她这个错误。
        猜你喜欢
        • 1970-01-01
        • 2023-03-29
        • 2017-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        • 2021-12-28
        相关资源
        最近更新 更多