试图限制字符串中的字符数

时间:2018-09-07 14:29:23

标签: c++

我试图将字符串item1,item2和item3限制为十个字母,如果它们长于十个字母,我希望程序产生一条语句并终止该程序。我也想使用price1,price2,price3来执行此操作,但是我还没有尝试过此操作,因为我停留在第一部分。我认为这应该类似于限制第一项。如何使用条件语句执行此操作? 这是我到目前为止的内容:

#include <iostream> 
#include <iomanip>

using namespace std;

int main () {

    string item1, item2, item3;
    int ten;
    ten=10;
    item1<"10";
    item2<"10";
    item3<"10";
    cout << "Enter names of 3 one-word items to purchase (each name must be less than 10 letters long): " <<endl;
    cin >> item1 >> item2 >> item3;

    if (item>=10)
    {
        cout<< "This item is more than 10 letters long" <<endl;
        return 0;
    }

    float price1, price2, price3, thousand;
    thousand=1000;
    cout << "You have purchased 3 items. Enter their prices in US Dollars (must be less than $1,000): " <<endl;
    cin >> price1 >> price2 >> price3;

}

2 个答案:

答案 0 :(得分:2)

std::string::size()是您要寻找的:

if (item1.size() > 10)
{
    std::cout << "This item is more than 10 letters long" << std::endl;
    return 0;
}

答案 1 :(得分:1)

您可能想要这样:

#include <iostream> 
#include <string> 

using namespace std;

int main() {
  string item1, item2, item3;

  cout << "Enter names of 3 one-word items to purchase (each name must be less than 10 letters long): " << endl;
  cin >> item1 >> item2 >> item3;

  if (item1.size() >= 10 || item2.size() >= 10 || item3.size() >= 10)
  {
    cout << "One of the items is more than 10 letters long" << endl;
    return 0;
  }
}

或者也许是这个

#include <iostream> 
#include <string> 

using namespace std;

int main() {
  string item1, item2, item3;

  cout << "Enter names of 3 one-word items to purchase (each name must be less than 10 letters long): " << endl;
  cin >> item1;
  if (item1.size() >= 10)
  {
    cout << "This item is more than 10 letters long" << endl;
    return 0;
  }
  cin >> item2;
  if (item2.size() >= 10)
  {
    cout << "This item is more than 10 letters long" << endl;
    return 0;
  }
  cin >> item3;
  if (item3.size() >= 10)
  {
    cout << "This item is more than 10 letters long" << endl;
    return 0;
  }
}

但这很尴尬。

此解决方案使用数组,可能正是您真正想要的:

#include <iostream> 
#include <string> 

using namespace std;

const int nbofitems = 3;   // modify here for changing the number of items

int main() {
  string items[nbofitems];

  cout << "Enter names of 3 one-word items to purchase (each name must be less than 10 letters long): " << endl;

  for (int i = 0; i < nbofitems; i++)
  {
    string item;
    cin >> item;
    if (item.size() >= 10)
    {
      cout << "This item is more than 10 letters long" << endl;
      return 0;
    }

    items[i] = item;
  }

  cout << "Items entered:\n";

  for (int i = 0; i < nbofitems; i++)
  {
    cout << "item " << i << ": " << items[i] << "\n";
  }
}

但是,仍有很多改进空间,例如使用std::vector代替原始数组。