私は割り当てに問題があり、スタックとグーグル全体を検索しましたが、問題を把握することはできません。テキストファイルとセグメンテーションフォールトを比較するC++(コアダンプ)
今のところ、私が今までに持っている唯一のコードは、ユーザーに文章を入力し、文章を別の文字列に分割することです。そして私はそれを私が途中で得たテキストファイルと比較する必要もあります。
最初の問題:単語を別の文字列に分割する私の方法は時々しか動作しません。例えば、私が "歴史人"と書くと、それは私にセグメンテーションの誤りを教えてくれるが、私が "歴史人"(最後にスペースを入れている)をタイプすればうまくいく。私は問題が何であるか混乱している。
2番目の問題は、文字列とテキストファイルを行単位で比較する方法を見つけることができないことです。文字列変数 "text"にファイル全体を格納するようです。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int noun(string n)
{
ifstream inputfile;
bool found = false; // set boolean value to false first
string text;
inputfile.open("nouns"); // open text file
if (!inputfile.is_open())
{ // checks to make sure file is open
cout << "Error" << endl;
}
while (getline(inputfile,text,' '))
{
if (n == text)
{
found = true;
cout << text;
}
}
inputfile.close(); // close the file
return found; // return true or false
}
int main()
{
string sent;
string word1, word2, word3, word4; // strings to parse the string 'sent'
cout << "Please enter a sentence" << endl;
getline (cin, sent);
int w1, w2, w3, w4 = 0; // positions in relation to the string
while (sent[w1] != ' ')
{ // while loop to store first word
word1 += sent[w1];
w1++;
}
w2 = w1 + 1;
while (sent[w2] != ' ')
{ // while loop to store second word
word2 += sent[w2];
w2++;
}
w3 = w2 + 1;
while (sent[w3] != ' ')
{ // while loop to store 3rd word
word3 += sent[w3];
w3++;
}
w4 = w3 + 1;
while (sent[w4] != sent[-1])
{ // while loop to store 4th word
word4 += sent[w4];
w4++;
}
cout << word1;
if (sent.empty())
{ // empty set returns "invalid sentence"
cout << "Invalid Sentence" << endl;
}
else if (noun(word1) == true)
{
cout << "This is valid according to rule 1" << endl;
}
return 0;
}
私は「履歴」という言葉を書いただけで、「歴史」を印刷しているということを忘れていました。 idkどこの感嘆符が – HCL212
から来ているのですか?なぜあなただけの 'cin >> word1;シン>> word2; ...? – SingerOfTheFall
コードを編集して問題の[mcve]に減らしてください。あなたの現在のコードには、問題の周辺にあるものが多く含まれています。通常、最小単位のサンプルは良い単位テストと似ています。 –