简体   繁体   English

C ++:将字符串追加到循环中第一个和最后一个数组索引的输出

[英]C++: Append string to output of first and last array index in loop

I tried to word the title as best as I could. 我尽了最大努力来写标题。 Here I have a function that indexes through two parallel arrays and then outputs them with some formatting. 在这里,我有一个函数可以对两个并行数组进行索引,然后以某种格式输出它们。

void outputTable(string salsa_jars[], int jars_sold[], int index[])
{
   int totalSold = 0;
   cout << setw(8) << "\nSalsa type sells: " << endl
        << "-------------------------------" << endl;

   for(int i = 0; i <= (SALSA_TYPES-1); i++)
   {
    totalSold += jars_sold[index[i]];
    cout << setw(15) << left << salsa_jars[index[i]]
         << setw(15) << right << jars_sold[index[i]] << endl;
   }

   cout << "-------------------------------" << endl
        << "Total sales: " << setw(17) << totalSold << endl;
}

在此处输入图片说明

What I'm trying to achieve is to add a string to the first and last outputs of the array. 我想要实现的是在数组的第一个和最后一个输出中添加一个字符串。 Below is my attempt. 以下是我的尝试。

void outputTable(string salsa_jars[], int jars_sold[], int index[])
{
   int totalSold = 0;
   cout << setw(8) << "\nSalsa type sells: " << endl
        << "-------------------------------" << endl;

   for(int i=0;i<=(SALSA_TYPES-1);i++)
   {
      if(i == 0){
      cout << setw(7) << left << salsa_jars[index[i]]
           << "(Highest)" << setw(14) << right
           << jars_sold[index[i]] << endl;
      }
      else if (i == (SALSA_TYPES-1)){
        cout << setw(7) << left << salsa_jars[index[i]]
        << "(Lowest)" << setw(15) << right
        << jars_sold[index[i]] << endl;
      }
      else{
        totalSold += jars_sold[index[i]];
        cout << setw(15) << left << salsa_jars[index[i]]
             << setw(15) << right << jars_sold[index[i]] << endl;
      }
    }  

    cout << "-------------------------------" << endl
         << "Total sales: " << setw(17) << totalSold << endl;
}

在此处输入图片说明

But the code seems redundant, and I couldn't think of any other way to do it. 但是代码似乎是多余的,而且我想不出其他方法来做到这一点。 If anyone has any pointers, I would appreciate it. 如果有人有任何指点,我将不胜感激。 Thanks. 谢谢。

Just prepare appropriate title for entry, and use common logic for displaying it: 只需准备适当的标题以供输入,并使用通用的逻辑进行显示即可:

for(int i=0;i<=(SALSA_TYPES-1);i++)
{
   string title = toString(salsa_jars[index[i]]);
   if(i == 0){
       title += " (Highest)";
   }
   else if (i == (SALSA_TYPES-1)){
     title += " (Lowest)";
   }
     totalSold += jars_sold[index[i]];
     cout << setw(15) << left << title
          << setw(15) << right << jars_sold[index[i]] << endl;
   }
 }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM