读取整行字符串,并用空格隔开

时间:2018-10-13 19:05:49

标签: c++

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

注意:用户只需要一键输入所有字符串,并用空格将它们分开。用户按下Enter键后,程序将需要用空格将其分隔。

例如: 输入: 2 哈克哈克 输出: 字串0:骇客 字串1:骇客 唯一字符串: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;
}

1 个答案:

答案 0 :(得分:-3)

#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';
}
相关问题