首页 > 解决方案 > 读取一整行字符串并用空格分隔它们

问题描述

我需要有关此问题的帮助。我尝试编写一个程序,允许用户输入多个输入字符串和字符串本身。问题出在我尝试分别拉出每个字符串时。

注意:用户只需一次性键入所有字符串并用空格分隔它们。一旦用户点击回车,程序将需要用空格分隔它们。

例如: 输入:2 hack hack 输出:字符串 0:hack 字符串 1:hack 唯一字符串:1

这是我的代码:

#include <iostream>
#include <string>
#define SIZE 10000
#define LENGTH 100

using namespace std;

int main(void)
{
    int a;                  // number of strings
    string str[SIZE];       // array of strings
    int count =0; 
    int unique_count = 0;


    // read the inputs
    cin >> a ;

    if (a>=1 && a<=SIZE)
    {
        while(count<a)
        {
            getline(cin, str[count]);
            count++;
        }
    }

    for(int i=0 ; i< count ; i++)
    {
        if(str[i].compare(str[i+1])==0)
            unique_count++;
        cout << "String " << i << " : " << str[i] << endl;
    }

    // return the output
    cout << "Unique string count: " <<  unique_count << endl;

    return 0;
}

标签: c++

解决方案


#include <cstddef>
#include <cctype>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>

std::istream& eatws(std::istream &is)
{
    int ch;
    while ((ch = is.peek()) != EOF && ch != '\n' && 
           std::isspace(static_cast<char unsigned>(ch)))
        is.get();
    return is;
}

int main()
{
    std::vector<std::string> words;
    char ch;
    std::string word;
    std::size_t unique_words = 0;
    while ((std::cin >> eatws >> std::noskipws >> ch) && ch != '\n' &&
           std::cin.putback(ch) && (std::cin >> word >> eatws)) {

        if (std::find(words.begin(), words.end(), word) == words.end())
            ++unique_words;
        words.push_back(word);

        if (std::cin.peek() == '\n')
            break;
    }

    for (std::size_t i{}; i < words.size(); ++i)
        std::cout << "String " << i << ": " << words[i] << '\n';

    std::cout << "Unique string count: " << unique_words << '\n';
}

推荐阅读