【问题标题】:How to verify assignment is done without error in string?如何验证分配是否在字符串中没有错误?
【发布时间】:2015-01-03 20:49:13
【问题描述】:

如果我想验证赋值操作怎么办?
链接http://ideone.com/pVE40h

#include <iostream>
#include <string>
using namespace std;

int main() {

    string str;
        int p;
    if  (p = 2)              // 1 case 
        cout << "assigned";
    else
        cout << "not assigned";

    if(str = "my string")   // 2 case 
        cout << "assigned"
    else
        cout << "not assigned";
return 0;
}

我的问题是,如果案例 1 有效,那么案例 2 应该有效,如果没有,为什么?应该这么简单? 我知道你们在这里发布的所有内容都在尝试捕捉东西,但我认为我应该那样工作??

【问题讨论】:

  • 阅读参考资料。如果有问题就会抛出。
  • 如果我想从头检查怎么办?
  • 然后捕获异常,就像您可能能够处理的任何其他异常一样。
  • 可能但不是好主意...
  • 您可以验证分配,但谁来验证验证?

标签: c++ string


【解决方案1】:
try
{
    str = "my_string";
    return 0;
}
catch(...)
{
    return 1;
}

【讨论】:

  • 我的问题是,如果案例 1 有效,那么案例 2 应该有效,如果没有,为什么?应该这么简单?我知道你们在这里发布的所有内容都尝试捕捉和其他东西,但我认为它应该这样工作??
  • 你改变了原来的代码。现在 case 1 是 int 可以隐式转换为 bool,case 2 是 std::string 不是。
  • 是的,你是对的@Matt McNabb,但是如果有的话,请回答这个问题?
  • @rupesh.yadav 抱歉,我不确定你还问什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 2017-11-27
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
相关资源
最近更新 更多