C++始めたばかりの初心者です。
作るプログラムは、文章を単語ごとに読む(英単語であり、数字などは無視。ピリオドやコンマは単語に含めない)。それが初めて単語であればlistに加えて単語の出現回数を1とする。また同じ単語が読まれた場合はlistに追加する代わりに出現回数を1とする。最後は単語をアルファベット順にソートするといった感じです。
また文章の最初は大文字ですが、大文字の単語も小文字の単語の場合と等しいとする。
私なりに作ってみましたが、未完成な上に間違いも多々あると思われます。
#include <iostream>
#include <string>
#include <list>
#include <cwctype>
using namespace std;
list<string> split(const string& s){
list<string> word;
string_size i = 0;
while(i != s.size()){
while(i != s.size() && isspace(s)) ++i;
string_size j = i;
while(j != s.size() && !isspace(s[j])) ++j;
if(i != j && std::iswalpha(s[j])){
{word.push_back(s.substr(i,j-i)); i = j;}
}
}
return word;
}
int main(){
string s;
int count = 0, i;
cin >> s;
list<string> word = split(s);
for(i = 0; i != NULL; i++){
cout << word << endl;
count++;
}
ご指摘ご回答、よろしくお願いします。
英単語を判定してlistに入れる
Re: 英単語を判定してlistに入れる
どうも、初級者な私ですがよろしくお願いします。suu さんが書きました:C++始めたばかりの初心者です。
未完成とは、どの辺まで完成済みなのでしょうか?suu さんが書きました:私なりに作ってみましたが、未完成な上に間違いも多々あると思われます。
また、こちらに貼りつけられたコードはテスト、最低限コンパイルは行っておりますか?
コンパイルすら通らないコードだと、回答者は「多分こうなのだろう。」と思って脳内で書き換えるか、いったん逆質問を投げかける等を行わなければならなくなります。
ちなみに今回貼りつけられたコードは、コンパイルが通りませんでした。
それとコードを貼りつける場合は特定のタグで囲っていただけると、見やすくそしてコピペもしやすくなりますので、投稿時等少し周りを見てみてください。
何を指摘していただきたく、また何を訊ねたいのでしょうか?suu さんが書きました:ご指摘ご回答、よろしくお願いします。
作成すべきプログラム、つまり目的は分かりました。
どこまでわかっているのかは分かりません。
どこが分かっていなくて先へ進めないのかも分かりません。
現在のコードがコンパイルエラーなのはわかりました。
Re: 英単語を判定してlistに入れる
このプログラムは list の代わりに map を使っているので解答ではありません。
でも、英単語の読み取りについては参考になりませんか?
でも、英単語の読み取りについては参考になりませんか?
#include <iostream> // cin
#include <iomanip> // setw
#include <cctype> // isalpha, tolower
#include <string>
#include <map>
using namespace std;
bool get_word(string& s)
{
char c;
s.clear();
do {
if (!cin.get(c)) return false;
} while (!isalpha(c));
do {
s += tolower(c);
if (!cin.get(c)) return true;
} while (isalpha(c));
return true;
}
int main()
{
map<string, int> m;
string s;
while (get_word(s)) m[s]++;
for (auto it = m.begin() ; it != m.end(); ++it)
cout << setw(5) << it->second << " " << it->first << endl;
}
Re: 英単語を判定してlistに入れる
list を使うと、
#include <iostream> // cin
#include <iomanip> // setw
#include <cctype> // isalpha, tolower
#include <algorithm> // find_if
#include <string>
#include <list>
using namespace std;
struct Cell {
string word;
int count;
Cell(const string& word) : word(word), count(1) {}
};
struct Match {
string word;
Match(const string& word) : word(word) {}
bool operator()(const Cell& x) const {
return x.word == word;
}
};
struct Comp {
bool operator()(const Cell& a, const Cell& b) const {
return a.word < b.word;
}
};
bool get_word(string& s)
{
char c;
s.clear();
do {
if (!cin.get(c)) return false;
} while (!isalpha(c));
do {
s += tolower(c);
if (!cin.get(c)) return true;
} while (isalpha(c));
return true;
}
int main()
{
list<Cell> m;
string s;
while (get_word(s)) {
auto it = find_if(m.begin(), m.end(), Match(s));
if (it == m.end()) m.push_back(Cell(s));
else it->count++;
}
m.sort(Comp());
for (const Cell& x : m)
cout << setw(5) << x.count << " " << x.word << endl;
}