C++关于向量和 for/while 循环的新手
我正在尝试制作一些东西,它将获取用户的输入行,将它们分成向量中的字符串,然后一次打印一个(每行 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 个,我尝试过的解决方案不断出现下标超出范围的错误。
I’m trying to make something that will take lines of input from the user, separate them into strings in a vector, then print them one at a time (8 per line).
so far this is what I’ve got:
#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);
}
}
}
I’m stuck on getting it to print them 8 at a time, the solutions I’ve tried keep getting subscript out of range errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西:
?
编辑:
上面的解决方案在末尾输出额外的空格/换行符。可以通过这样的事情来避免:
Something like this:
?
EDIT:
the solution above outputs extra space/newline at the end. It can be avoided by something like this:
使用索引遍历向量:
sep(idx)
是什么?它是在第 idxth 个单词之后打印的分隔符。这是(idx+1)%8 == 0
。idx+1 == svec.size()
中。一个简单的方法是使用三元运算符:
如果你不喜欢这样,
Walk over your vector with an index:
What is this
sep(idx)
? It is the separator to print after the idxth word. This is(idx+1)%8 == 0
.idx+1 == svec.size()
.An easy way to do this is with the ternary operator:
If you don't like that,
通常,您使用
for
循环子句迭代向量。因此,如果您想打印vector
的所有元素,您必须进行如下操作:编辑: 正如 Vlad 已正确发布的那样,您还可以使用数组索引,在列表中效率较低,但在向量中效率相同。
Normally you iterate over a vector using a
for
loop clause. So if you want to print all elements of yourvector<string>
you have to make something like this:EDIT: as Vlad has posted correctly, you can also use array indices, which are less efficient in lists, but equally efficient with vectors.