首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用vector<string>将八个单词打印成一行?

如何使用vector<string>将八个单词打印成一行?
EN

Stack Overflow用户
提问于 2020-02-29 11:55:03
回答 1查看 41关注 0票数 0

I试图使一个程序在用户输入他们的sentence.Its后将8个单词写到一行中,而我不知道如何将8个单词输入一行。

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;

vector<string> sentence;
string sente = "";

void print(string, string);

template<typename T>
void print(vector<T>& v, string)
{

    cout << "Enter your sentence " << endl;

    getline(cin, sente);
    sentence.push_back(sente);

    for (auto const elem: sentence)
    {
        cout << elem;
    }

}

int main()
{
    print(sentence,sente);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-29 12:29:49

使用全局变量通常不是一个好做法。

此外,您也不需要为用例提供额外的向量。

看看下面的代码,您可以巧妙地在用例中使用istringstream

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <sstream>

void print()
{

    std::string sente;

    std::cout << "Enter your sentence " << std::endl;

    getline(std::cin, sente);

    // Used to split string around spaces. 
    std::istringstream ss(sente);

    int wordCountPerLine = 0;
    int requiredWordsPerLine = 8;

    // Traverse through all words 
    do { 
        // Read a word 
        std::string word; 
        ss >> word; 

        // Print the read word 
        std::cout << word << " ";

        wordCountPerLine++;

        if(wordCountPerLine % requiredWordsPerLine == 0){
            std::cout<<std::endl;
            wordCountPerLine = 0;
        }

        // While there is more to read 
    } while (ss); 
}

int main()
{
    print();
}

如果有任何疑问,请随便问。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60464871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档