c++ - 读取一整行字符串并用空格分隔它们
问题描述
我需要有关此问题的帮助。我尝试编写一个程序,允许用户输入多个输入字符串和字符串本身。问题出在我尝试分别拉出每个字符串时。
注意:用户只需一次性键入所有字符串并用空格分隔它们。一旦用户点击回车,程序将需要用空格分隔它们。
例如: 输入: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;
}
解决方案
#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';
}
推荐阅读
- sql - PIVOTING IN SQL - 将 col 转换为行
- php - 通过直接链接锁定对 PDF 文件的访问
- visual-studio-2013 - SDL_init() 函数使 VS 中的调试变得迟缓
- r - 弹出模式中的闪亮模块化输入在关闭时不会被写入响应值 [flexdashboard/shinydashboard]
- nativescript - 将动态创建的自定义 Angular 组件添加到 Nativescript 中的布局
- java - Spring Boot 1.3.8 + 休眠。JPA 端 ConstraintValidator 的双重初始化
- class - svcutils 和 COM 类可见
- sql - SQL删除查询忽略错误并继续
- c - 值未正确分配给变量
- python - 使用推导在字典的值字段中附加元素