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

Trying to limit the number of characters in the string

本文关键字:字符 字符串      更新时间:2023-10-16

我试图将字符串 item1、item2 和 item3 限制为十个字母,如果它们长于 10 个字母,我希望程序生成一个语句并终止程序。我也想用 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;
}

std::string::size()就是你要找的:

if (item1.size() > 10)
{
std::cout << "This item is more than 10 letters long" << std::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 >> 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而不是原始数组。