【问题标题】:C++ Novice regarding Vectors and for/while loops关于向量和 for/while 循环的 C++ 新手
【发布时间】:2011-10-13 09:55:49
【问题描述】:

我正在尝试做一些东西,它会接受用户输入的行,将它们分成向量中的字符串,然后一次打印一个(每行 8 个)。 到目前为止,这就是我所拥有的:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

int main(void)
{
    using namespace std;

    vector<string> svec1;
    string temp;
    while(getline(cin, temp)) //stores lines of text in temp
    {
        if(temp.empty()) //checks if temp is empty, exits loop if so.
            break;
        stringstream ss(temp);
        string word;
        while(ss >> word) //takes each word and stores it in a slot on the vector svec1
        {
            svec1.push_back(word);
        }            
    }        
}

我一直坚持让它一次打印 8 个,我尝试过的解决方案不断出现下标超出范围的错误。

【问题讨论】:

  • 并确保添加您的打印解决方案,以便我们帮助您解决下标错误。
  • 你在哪里一次打印 8 个?
  • 如此短的 sn-ps 应在此处内联,以便即使在 cast pastebin 关闭时您的问题仍然有效(注意:已经为您做过)

标签: c++ loops vector for-loop while-loop


【解决方案1】:

类似这样的:

for(int i = 0; i < svec1.size(); i++)
{
    cout << svec1[i];
    if ((i+1) % 8 == 0)
        cout << endl;
    else
        cout << " ";
}

?

编辑:
上面的解决方案在最后输出额外的空格/换行符。可以通过以下方式避免:

for(int i = 0; i < svec1.size(); i++)
{
    if (i == 0)
        /*do nothing or output something at the beginning*/;
    else if (i % 8 == 0)
        cout << endl; /*separator between lines*/
    else
        cout << " "; /*separator between words in line*/
    cout << svec1[i];
}

【讨论】:

  • 不确定如何直接回复所以 facebook 风格它是 nathan:我在第 50 次无法正常工作后废弃了它,反正这是一个可怕的混乱。 leon:从一本书中学习C++,这是练习之一> phresnel:谢谢,我以后会记住这一点。 @Vlad 我现在就试试,非常感谢
  • @user863492:您可以在问题下方使用 cmets 下方的“添加评论”链接。
  • @Vlad:将 int index 更改为 int i
【解决方案2】:

用索引遍历你的向量:

for (unsigned int idx = 0; idx < svec1.size(); ++idx) {
   std::cout << svec[idx] << sep(idx); // sep(idx) is conceptual; described below
}

这是什么sep(idx)?它是在 idxth 单词之后打印的分隔符。这是

  • 在一行上打印了八个单词后的换行符。 idx 将是 7、15、23 等:比 8 的整数倍差一倍。在代码中,(idx+1)%8 == 0
  • 向量中最后一项的换行符;您可能希望最后一项后跟换行符。在代码idx+1 == svec.size()
  • 否则为空格。

一个简单的方法是使用三元运算符:

for (unsigned int idx = 0; idx < svec1.size(); ++idx) {
   const char * sep = (((idx+1)%8 == 0) || (idx+1 == svec.size())) ? "\n" : " ";
   std::cout << svec[idx] << sep;
}

如果你不喜欢,

for (unsigned int idx = 0; idx < svec1.size(); ++idx) {
   const char * sep;
   if (((idx+1)%8 == 0) || (idx+1 == svec.size())) {
      sep = "\n";
   }
   else {
      sep = " ";
   }
   std::cout << svec[idx] << sep;
}

【讨论】:

    【解决方案3】:

    通常您使用for 循环子句对向量进行迭代。因此,如果您想打印 vector&lt;string&gt; 的所有元素,您必须这样做:

    for(vector<string>::iterator it = myvec.begin(); it != myvec.end(); ++it) {
        cout << *it;
    }
    

    编辑: 正如 Vlad 正确发布的那样,您还可以使用数组索引,这在列表中效率较低,但在向量中同样有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 2010-10-07
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多